Saturday 10 August 2013

Top Most Simple GUI Hello World in J2ME

Your Entry class should be like this.



package test.myapp;

import java.io.PrintStream;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public final class studentBT extends MIDlet
    implements CommandListener
{

    public studentBT()
    {
        menu = new List("studentBT", 3, elements, null);
        isInit = false;
        menu.addCommand(EXIT_CMD);
        menu.addCommand(OK_CMD);
        menu.setCommandListener(this);
    }

    public void startApp()
    {
        if(!isInit)
            studentCell = new GUIstudentCell(this);
    }

    protected void destroyApp(boolean flag)
    {
        if(studentCell != null)
            studentCell.destroy();
    }

    protected void pauseApp()
    {
    }

    public void commandAction(Command command, Displayable displayable)
    {
        if(command == EXIT_CMD)
        {
            destroyApp(true);
            notifyDestroyed();
            return;
        }
        switch(menu.getSelectedIndex())
        {
        case 1: // '\001'
            studentCell = new GUIstudentCell(this);
            break;

        default:
            System.err.println("Unexpected choice...");
            break;

        case 0: // '\0'
            break;
        }
        isInit = true;
    }

    void show()
    {
        Display.getDisplay(this).setCurrent(menu);
    }

    Displayable getDisplayable()
    {
        return menu;
    }

    static final int ALERT_TIMEOUT = 2000;
    private static final String elements[] = {
        "My Hello World App", "Part I"
    };
    private final Command EXIT_CMD = new Command("Exit", 7, 2);
    private final Command OK_CMD = new Command("Ok", 1, 1);
    private final List menu;
    private GUIstudentCell studentCell;
    private boolean isInit;

}


//Your second class of GUI should be like GUIstudentCell class


package test.myapp;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.lcdui.*;

// Referenced classes of package test.myapp:
//            BTstudentCell, studentBT

final class GUIstudentCell
    implements CommandListener
{

    GUIstudentCell(studentBT studentbt)
    {
        matricula = new TextField("Registration", "", 5, 2);
        formulario = new TextField("Options", "", 5, 2);
        Q1 = new TextField("Q1", "", 10, 0);
        Q2 = new TextField("Q2", "", 10, 0);
        Q3 = new TextField("Q3", "", 10, 0);
        Q4 = new TextField("Q4", "", 10, 0);
        Q5 = new TextField("Q5", "", 10, 0);
        lanota = new TextField("Note", "", 10, 0);
        cadena = "vacia";
        yabuscado = false;
        primeravez = true;
        parent = studentbt;
        bt_client = new BTstudentCell(this);
        mainScreen.addCommand(SCR_MAIN_BACK_CMD);
        mainScreen.addCommand(SCR_MAIN_SEARCH_CMD);
        try
        {
            logo = new ImageItem("", Image.createImage("/log-mp.gif"), 771, "");
            mainScreen.append(logo);
        }
        catch(IOException ioexception)
        {
            throw new RuntimeException("Unable to Submit: " + ioexception);
        }
        mainScreen.append(matricula);
        mainScreen.append(formulario);
        mainScreen.append("Write the results of the five issues");
        mainScreen.append(Q1);
        mainScreen.append(Q2);
        mainScreen.append(Q3);
        mainScreen.append(Q4);
        mainScreen.append(Q5);
        galgaindicadora = new Gauge("Starting ...", false, -1, 2);
        galgaindicadora.setLayout(3);
        mainScreen.setCommandListener(this);
        listScreen.addCommand(SCR_IMAGES_BACK_CMD);
        listScreen.addCommand(SCR_IMAGES_LOAD_CMD);
        listScreen.setCommandListener(this);
        imageScreen.addCommand(SCR_SHOW_BACK_CMD);
        imageScreen.setCommandListener(this);
    }

    public void commandAction(Command command, Displayable displayable)
    {
        if(command == SCR_MAIN_BACK_CMD)
        {
            destroy();
            parent.destroyApp(true);
            parent.notifyDestroyed();
            return;
        }
        if(command == SCR_MAIN_SEARCH_CMD)
        {
            mainScreen.removeCommand(SCR_MAIN_SEARCH_CMD);
            mainScreen.insert(1, galgaindicadora);
            Display.getDisplay(parent).setCurrentItem(logo);
            bt_client.requestSearch();
            return;
        }
        if(command == SCR_SEARCH_CANCEL_CMD)
        {
            bt_client.cancelSearch();
            Display.getDisplay(parent).setCurrent(mainScreen);
            return;
        }
        if(command == SCR_IMAGES_BACK_CMD)
        {
            Display.getDisplay(parent).setCurrent(mainScreen);
            return;
        }
        if(command == SCR_IMAGES_LOAD_CMD)
        {
            Form form = new Form("Correcting...");
            form.addCommand(SCR_LOAD_CANCEL_CMD);
            form.setCommandListener(this);
            form.append(new Gauge("and waiting for the PC....", false, -1, 2));
            Display.getDisplay(parent).setCurrent(form);
            List list = (List)displayable;
            bt_client.requestLoad(list.getString(list.getSelectedIndex()));
            return;
        }
        if(command == SCR_LOAD_CANCEL_CMD)
        {
            bt_client.cancelLoad();
            Display.getDisplay(parent).setCurrent(listScreen);
            return;
        }
        if(command == SCR_SHOW_BACK_CMD)
        {
            Display.getDisplay(parent).setCurrent(listScreen);
            return;
        } else
        {
            return;
        }
    }

    void completeInitialization(boolean flag)
    {
        if(flag)
        {
            Display.getDisplay(parent).setCurrent(mainScreen);
            return;
        } else
        {
            Alert alert = new Alert("Trouble", "Bluetooth is not enabled", null, AlertType.ERROR);
            alert.setTimeout(2000);
            mainScreen.removeCommand(SCR_MAIN_SEARCH_CMD);
            Display.getDisplay(parent).setCurrent(alert, mainScreen);
            return;
        }
    }

    void destroy()
    {
        bt_client.destroy();
    }

    void informSearchError(String s)
    {
        Alert alert = new Alert("Error", s, null, AlertType.ERROR);
        alert.setTimeout(2000);
        mainScreen.delete(1);
        mainScreen.addCommand(SCR_MAIN_SEARCH_CMD);
        Display.getDisplay(parent).setCurrent(alert, mainScreen);
    }

    void informLoadError(String s)
    {
        Alert alert = new Alert("Error", s, null, AlertType.ERROR);
        alert.setTimeout(2000);
        Display.getDisplay(parent).setCurrent(alert, listScreen);
    }

    void showImage(String s)
    {
        lanota.setString(s);
        if(primeravez)
        {
            mainScreen.insert(1, lanota);
            primeravez = false;
        }
        Display.getDisplay(parent).setCurrent(mainScreen);
        Display.getDisplay(parent).setCurrentItem(logo);
    }

    boolean showImagesNames(Hashtable hashtable)
    {
        Enumeration enumeration = hashtable.keys();
        if(!enumeration.hasMoreElements())
        {
            informSearchError("No found services");
            return false;
        }
        for(; listScreen.size() != 0; listScreen.delete(0));
        String s = "";
        String s1;
        for(; enumeration.hasMoreElements(); listScreen.append(s1, null))
        {
            s1 = (String)enumeration.nextElement();
            if(s1.indexOf("ke (png)") > 0)
                s1 = "Active Participation";
        }

        Display.getDisplay(parent).setCurrent(listScreen);
        if(!yabuscado)
        {
            mainScreen.removeCommand(SCR_SEARCH_CANCEL_CMD);
            mainScreen.addCommand(SCR_SHOW_BACK_CMD);
            mainScreen.delete(1);
            yabuscado = true;
        }
        return true;
    }

    private final Command SCR_MAIN_BACK_CMD = new Command("Salir", 7, 1);
    private final Command SCR_MAIN_SEARCH_CMD = new Command("Inicia", 4, 2);
    private final Command SCR_SEARCH_CANCEL_CMD = new Command("Cancel", 2, 3);
    private final Command SCR_IMAGES_BACK_CMD = new Command("Volver", 2, 3);
    private final Command SCR_IMAGES_LOAD_CMD = new Command("Enviar", 4, 2);
    private final Command SCR_LOAD_CANCEL_CMD = new Command("Cancel", 2, 3);
    private final Command SCR_SHOW_BACK_CMD = new Command("Elegir", 4, 2);
    private final Form mainScreen = new Form("Liqvid BlueTooth Polling");
    public TextField matricula;
    public TextField formulario;
    public TextField Q1;
    public TextField Q2;
    public TextField Q3;
    public TextField Q4;
    public TextField Q5;
    public TextField lanota;
    public ImageItem logo;
    public Gauge galgaindicadora;
    String cadena;
    Image onImage;
    private final List listScreen = new List("Possibilities", 3);
    private final Form imageScreen = new Form("Staff");
    private studentBT parent;
    public boolean yabuscado;
    public boolean primeravez;
    private BTstudentCell bt_client;
}


// your main controller class should be like this



package test.myapp;

import java.io.*;
import java.util.*;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.TextField;

// Referenced classes of package GieFai:
//            GUIstudentCell

final class BTstudentCell
    implements Runnable, DiscoveryListener
{

    BTstudentCell(GUIstudentCell guistudentcell)
    {
        notac = 0;
        state = 0;
        devices = new Vector();
        records = new Vector();
        base = new Hashtable();
        parent = guistudentcell;
        processorThread = new Thread(this);
        processorThread.start();
    }

    public void run()
    {
        boolean flag = false;
        try
        {
            LocalDevice localdevice = LocalDevice.getLocalDevice();
            midirecBT = localdevice.getBluetoothAddress();
            if(localdevice.setDiscoverable(0));
            discoveryAgent = localdevice.getDiscoveryAgent();
            flag = true;
        }
        catch(Exception exception)
        {
            System.err.println("Unable to initialize bluetooth:" + exception);
        }
        parent.completeInitialization(flag);
        if(!flag)
        {
            return;
        } else
        {
            uuidSet = new UUID[2];
            uuidSet[0] = new UUID(4353L);
            uuidSet[1] = PICTURES_SERVER_UUID;
            attrSet = new int[1];
            attrSet[0] = 17185;
            processImagesSearchDownload();
            return;
        }
    }

    public void deviceDiscovered(RemoteDevice remotedevice, DeviceClass deviceclass)
    {
        if(devices.indexOf(remotedevice) == -1)
            devices.addElement(remotedevice);
    }

    public void inquiryCompleted(int i)
    {
        discType = i;
        synchronized(this)
        {
            notify();
        }
    }

    public void servicesDiscovered(int i, ServiceRecord aservicerecord[])
    {
        for(int j = 0; j < aservicerecord.length; j++)
            records.addElement(aservicerecord[j]);

    }

    public void serviceSearchCompleted(int i, int j)
    {
        int k = -1;
        int l = 0;
        do
        {
            if(l >= searchIDs.length)
                break;
            if(searchIDs[l] == i)
            {
                k = l;
                break;
            }
            l++;
        } while(true);
        if(k == -1)
            System.err.println("Unexpected transaction index: " + i);
        else
            searchIDs[k] = -1;
        for(int i1 = 0; i1 < searchIDs.length; i1++)
            if(searchIDs[i1] != -1)
                return;

        synchronized(this)
        {
            notify();
        }
    }

    void requestSearch()
    {
        synchronized(this)
        {
            notify();
        }
    }

    void cancelSearch()
    {
        synchronized(this)
        {
            if(state == 1)
                discoveryAgent.cancelInquiry(this);
            else
            if(state == 2)
            {
                for(int i = 0; i < searchIDs.length; i++)
                    discoveryAgent.cancelServiceSearch(searchIDs[i]);

            }
        }
    }

    void requestLoad(String s)
    {
        synchronized(this)
        {
            imageNameToLoad = s;
            notify();
        }
    }

    void cancelLoad()
    {
        isDownloadCanceled = true;
    }

    void destroy()
    {
        synchronized(this)
        {
            isClosed = true;
            isDownloadCanceled = true;
            notify();
        }
        try
        {
            processorThread.join();
        }
        catch(InterruptedException interruptedexception) { }
    }

    private synchronized void processImagesSearchDownload()
    {
        do
        {
label0:
            {
                do
                {
                    do
                    {
                        if(isClosed)
                            break label0;
                        state = 0;
                        try
                        {
                            wait();
                        }
                        catch(InterruptedException interruptedexception)
                        {
                            System.err.println("Unexpected interruption: " + interruptedexception);
                            return;
                        }
                        if(isClosed)
                            return;
                        if(!searchDevices())
                            return;
                    } while(devices.size() == 0);
                    if(!searchServices())
                        return;
                } while(records.size() == 0 || !presentUserSearchResults());
                do
                {
                    isDownloadCanceled = false;
                    try
                    {
                        wait();
                    }
                    catch(InterruptedException interruptedexception1)
                    {
                        System.err.println("Unexpected interruption: " + interruptedexception1);
                        return;
                    }
                    if(isClosed)
                        return;
                    if(imageNameToLoad == null)
                        break;
                    String s = loadImage();
                    if(isClosed)
                        return;
                    if(!isDownloadCanceled)
                        parent.showImage(s);
                } while(true);
            }
        } while(true);
    }

    private boolean searchDevices()
    {
        state = 1;
        devices.removeAllElements();
        try
        {
            discoveryAgent.startInquiry(0x9e8b33, this);
        }
        catch(BluetoothStateException bluetoothstateexception)
        {
            System.err.println("Can't start inquiry now: " + bluetoothstateexception);
            parent.informSearchError("Can't start device search");
            return true;
        }
        try
        {
            wait();
        }
        catch(InterruptedException interruptedexception)
        {
            System.err.println("Unexpected interruption: " + interruptedexception);
            return false;
        }
        if(isClosed)
            return false;
        switch(discType)
        {
        case 7: // '\007'
            parent.informSearchError("I can not find devices...");
            // fall through

        case 5: // '\005'
            devices.removeAllElements();
            break;

        case 0: // '\0'
            if(devices.size() == 0)
                parent.informSearchError("I can not find devices");
            break;

        default:
            System.err.println("system error: unexpected device discovery code: " + discType);
            destroy();
            return false;
        }
        return true;
    }

    private boolean searchServices()
    {
        state = 2;
        records.removeAllElements();
        searchIDs = new int[devices.size()];
        boolean flag = false;
        for(int i = 0; i < devices.size(); i++)
        {
            RemoteDevice remotedevice = (RemoteDevice)devices.elementAt(i);
            try
            {
                searchIDs[i] = discoveryAgent.searchServices(attrSet, uuidSet, remotedevice, this);
            }
            catch(BluetoothStateException bluetoothstateexception)
            {
                System.err.println("Can't search services for: " + remotedevice.getBluetoothAddress() + " due to " + bluetoothstateexception);
                searchIDs[i] = -1;
                continue;
            }
            flag = true;
        }

        if(!flag)
        {
            parent.informSearchError("I can not find options");
            return true;
        }
        try
        {
            wait();
        }
        catch(InterruptedException interruptedexception)
        {
            System.err.println("Unexpected interruption: " + interruptedexception);
            return false;
        }
        if(isClosed)
            return false;
        if(records.size() == 0)
            parent.informSearchError("I have not found options");
        return true;
    }

    private boolean presentUserSearchResults()
    {
        base.clear();
        for(int i = 0; i < records.size(); i++)
        {
            ServiceRecord servicerecord = (ServiceRecord)records.elementAt(i);
            DataElement dataelement = servicerecord.getAttributeValue(17185);
            if(dataelement == null)
            {
                System.err.println("Unexpected service - missed attribute");
                continue;
            }
            String s;
            Object obj;
            for(Enumeration enumeration = (Enumeration)dataelement.getValue(); enumeration.hasMoreElements(); base.put(s, obj))
            {
                DataElement dataelement1 = (DataElement)enumeration.nextElement();
                s = (String)dataelement1.getValue();
                obj = base.get(s);
                if(obj != null)
                {
                    Vector vector;
                    if(obj instanceof ServiceRecord)
                    {
                        vector = new Vector();
                        vector.addElement(obj);
                    } else
                    {
                        vector = (Vector)obj;
                    }
                    vector.addElement(servicerecord);
                    obj = vector;
                } else
                {
                    obj = servicerecord;
                }
            }

        }

        return parent.showImagesNames(base);
    }

    private String loadImage()
    {
        ServiceRecord aservicerecord[];
        int i;
        if(imageNameToLoad == null)
        {
            System.err.println("Error: imageNameToLoad=null");
            return null;
        }
        aservicerecord = null;
        Object obj = base.get(imageNameToLoad);
        if(obj == null)
        {
            System.err.println("Error: no record for: " + imageNameToLoad);
            return null;
        }
        if(obj instanceof ServiceRecord)
        {
            aservicerecord = (new ServiceRecord[] {
                (ServiceRecord)obj
            });
        } else
        {
            Vector vector = (Vector)obj;
            aservicerecord = new ServiceRecord[vector.size()];
            for(int j = 0; j < vector.size(); j++)
                aservicerecord[j] = (ServiceRecord)vector.elementAt(j);

        }
        i = 0;
_L3:
        if(i >= aservicerecord.length) goto _L2; else goto _L1
_L1:
        StreamConnection streamconnection;
        String s;
        streamconnection = null;
        s = null;
        if(isDownloadCanceled)
            return null;
        try
        {
            s = aservicerecord[i].getConnectionURL(0, false);
            streamconnection = (StreamConnection)Connector.open(s);
        }
        catch(IOException ioexception)
        {
            System.err.println("I can not connect to: " + s);
            continue; /* Loop/switch isn't completed */
        }
        String s1 = ";m=" + parent.matricula.getString();
        s1 = s1 + ";f=" + parent.formulario.getString();
        s1 = s1 + ";u=" + midirecBT;
        s1 = s1 + ";Q1=" + parent.Q1.getString();
        s1 = s1 + ";Q2=" + parent.Q2.getString();
        s1 = s1 + ";Q3=" + parent.Q3.getString();
        s1 = s1 + ";Q4=" + parent.Q4.getString();
        s1 = s1 + ";Q5=" + parent.Q5.getString() + ";";
        imageNameToLoad = imageNameToLoad + s1;
        try
        {
            OutputStream outputstream = streamconnection.openOutputStream();
            outputstream.write(imageNameToLoad.length());
            outputstream.write(imageNameToLoad.getBytes());
            outputstream.flush();
            outputstream.close();
        }
        catch(IOException ioexception1)
        {
            System.err.println("I can not send data to: " + s);
            try
            {
                streamconnection.close();
            }
            catch(IOException ioexception2) { }
            continue; /* Loop/switch isn't completed */
        }
        Object obj1 = null;
        boolean flag = false;
        InputStream inputstream = streamconnection.openInputStream();
        int l = inputstream.read() << 8;
        l |= inputstream.read();
        String s3 = "H" + l + "*";
        int k = l;
        notac = l;
        if(l < 0)
            throw new IOException("I do not receive the note");
        inputstream.close();
        try
        {
            streamconnection.close();
        }
        catch(IOException ioexception3) { }
        break MISSING_BLOCK_LABEL_766;
        IOException ioexception4;
        ioexception4;
        System.err.println("I can not get the memo of: " + s);
        try
        {
            streamconnection.close();
        }
        catch(IOException ioexception5) { }
        break MISSING_BLOCK_LABEL_766;
        Exception exception;
        exception;
        try
        {
            streamconnection.close();
        }
        catch(IOException ioexception6) { }
        throw exception;
        String s2 = " (";
        int i1 = 0;
        boolean flag1 = true;
        for(int j1 = 1; j1 <= 5; j1++)
        {
            byte byte0 = 2;
            i1 += notac % byte0;
            s2 = s2 + notac % byte0;
            notac = notac - notac % byte0;
            notac = notac / 2;
        }

        s2 = i1 + s2 + ")";
        notac = i1;
        return s2;
        i++;
          goto _L3
_L2:
        return null;
    }

    private String leeCadena(StreamConnection streamconnection)
    {
        String s = null;
        InputStream inputstream = null;
        try
        {
            inputstream = streamconnection.openInputStream();
            int i = inputstream.read();
            if(i <= 0)
                throw new IOException("Can't read name length");
            byte abyte0[] = new byte[i];
            int k;
            for(int j = 0; j != abyte0.length; j += k)
            {
                k = inputstream.read(abyte0, j, abyte0.length - j);
                if(k == -1)
                    throw new IOException("Can't read name data");
            }

            s = new String(abyte0);
        }
        catch(IOException ioexception)
        {
            System.err.println(ioexception);
        }
        if(inputstream != null)
            try
            {
                inputstream.close();
            }
            catch(IOException ioexception1) { }
        return s;
    }

    public void escribeCadena(StreamConnection streamconnection, String s)
    {
        try
        {
            OutputStream outputstream = streamconnection.openOutputStream();
            outputstream.write(s.length());
            outputstream.write(s.getBytes());
            outputstream.flush();
            outputstream.close();
        }
        catch(IOException ioexception)
        {
            System.err.println("Can't write to server ");
            try
            {
                streamconnection.close();
            }
            catch(IOException ioexception1) { }
        }
    }

    private static final UUID PICTURES_SERVER_UUID = new UUID("F0E0D0C0B0A555908070605040302010", false);
    private static final int IMAGES_NAMES_ATTRIBUTE_ID = 17185;
    private static final int READY = 0;
    public int notac;
    public String midirecBT;
    private static final int DEVICE_SEARCH = 1;
    private static final int SERVICE_SEARCH = 2;
    private int state;
    private DiscoveryAgent discoveryAgent;
    private GUIstudentCell parent;
    private boolean isClosed;
    private Thread processorThread;
    private Vector devices;
    private Vector records;
    private int discType;
    private int searchIDs[];
    private String imageNameToLoad;
    private Hashtable base;
    private boolean isDownloadCanceled;
    private UUID uuidSet[];
    private int attrSet[];

}



LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt