Tuesday, August 30, 2011

Simple Mobile Game in J2ME(Canvas Continued):-

0 comments
In previous tutorial we learned about a simple canvas class.
In this tutoial we will try to create a simple gaming interface using Canvas.
In this code we have created a canvas class and created its object in our Midlet.
Inside the constructor SampleCanvas() , we read a image and then create a sprite ,which represent the moving item inside the game.
You can download sample sprite image from here .You have to paste it inside source(src) folder of your project.
Then whenever a key is pressed ,the canvas function keyPressed() is called automatically.
we define this function to detect the key pressed and then call the check function for the first time(when thread is not started ).
And thereafter it changes the direction of movement by changing keycode.
Check function is created to start the thread and hence the movement of sprite.
Thread ,when started calls the handleaction function which decides the direction  of movement of sprite according to the key pressed.
And finally repaint function changes the position of sprite accordingly.

We conclude this tutorial here and  will discuss in depth about various other provisions that can be made in subsequent tutorial.

Code:-

import java.io.IOException;
import java.lang.Thread;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.Sprite;


public class GameMidlet extends MIDlet {

    private SampleCanvas gameCanvas;
    private Thread t=null;
    private Display d;

    public void startApp() {
        try {
            this.gameCanvas = new SampleCanvas();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        d = Display.getDisplay(this);
        d.setCurrent(gameCanvas);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    
    }
}


class SampleCanvas extends Canvas implements Runnable {
    int     x, y;           // Location of cross hairs
    String  event = "";     // Last key event type
    int     keyCode;        // Last keyCode pressed
    int     w, h;           // width and height of the canvas
    Image img;
    Sprite sprite;
    boolean flag;
    Thread t1;
    SampleCanvas() throws IOException {
       img=Image.createImage("/sprite.png");
       sprite=new Sprite(img);
        w = getWidth();
        h = getHeight();

    }

    protected void keyPressed(int key) {
        keyCode = key;
        event = "Pressed";
        if(t1==null)
        Check();
    }

   protected void Check()
   {
        flag=true;
        t1=new Thread(this);
        t1.start();
   }


        void handleActions(int keyCode) {
        int action = getGameAction(keyCode);
        switch (action) {
            case LEFT:
            x -= 1;
            break;
            case RIGHT:
            x += 1;
            break;
            case UP:
            y -= 1;
            break;
            case DOWN:
            y += 1;
            break;
        }
    }

    protected void paint(Graphics g) {
        g.setColor(255,255, 255);
        g.fillRect(0, 0, w, h);
        sprite.setRefPixelPosition(0,0) ;
        sprite.setPosition(x, y);
        sprite.paint(g) ;
      }

    public void run() {
       while(flag)
       {
            handleActions(keyCode);
            repaint();
            try {
                Thread.sleep(20);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
       }
     
    }
}


Monday, August 29, 2011

RecordStore in J2ME :- (Continued)

0 comments
In previous tutorial we learned how to create a simple recordstore.
In this tutorial we will also learn deletion and updation of records.
But keep 1 thing in mind , delete the topmost record only (it will also work otherwise ,but will break the sequence as the deleted record is left as a null pointer).
One more thing , when you run this code on toolkit ,it will remember the last data entered,to flush it,use clean and build option or change the recordstore name.

 Code:-

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

public class Midlet1 extends MIDlet    implements CommandListener, Runnable
{
    private Form form;
 private Form form1;
 private Form form2;
 private Form form3;
 private TextField t;
 private TextField t1;
 private TextField t2;
 private TextField t3;
 private Command write;
 private Command read;
 private Command back;
 private Command delete;
 private Command confirmd;
 private Command confirmu;
 private Command update;
 private RecordStore recordStore;
 private Alert alert;
 public Midlet1()
 {
     form = new Form("Record");
     form2 = new Form("Deletion Form");
     form3 = new Form("Updation Form");
     read = new Command("Read", 1, 1);
     write = new Command("Write", 1, 1);
     delete = new Command("Delete", 1, 1);
     back = new Command("Back", 1, 1);
     confirmd = new Command("Confirm Delete", 1, 1);
     confirmu = new Command("Confirm Update", 1, 1);
     update = new Command("Update Record", 1, 1);
     form.addCommand(write);
     form.addCommand(read);
     form.addCommand(delete);
     form.addCommand(update);
     form2.addCommand(confirmd);
     form2.addCommand(back);
     form3.addCommand(back);
     form3.addCommand(confirmu);
     form.setCommandListener(this);
     form2.setCommandListener(this);
     form3.setCommandListener(this);
     try{
         recordStore = RecordStore.openRecordStore("My Record Store", true);
        }
     catch(Exception ex)
     { }
     t = new TextField("Enter data", "", 30, 0);
     t1 = new TextField("Enter record Id to be Deleted", "", 30, 0);
     t2 = new TextField("Enter record Id to be Updated", "", 30, 0);
     t3 = new TextField("Enter data", "", 30, 0);
     form.append(t);
     form2.append(t1);
     form3.append(t2);
     form3.append(t3);
 }
 public void startApp()
 {
     Display.getDisplay(this).setCurrent(form);
 }     public void pauseApp()
    {
    }
 public void destroyApp(boolean flag)
 {    }
 public void commandAction(Command c, Displayable d)
 {
     if(c == write)
         try{
             byte bytestream[] = t.getString().getBytes();
             int i = recordStore.addRecord(bytestream, 0, bytestream.length);
            Alert a = new Alert("Done", "Record Added",null, null);
            a.setTimeout(1000);
            Display.getDisplay(this).setCurrent(a);
         }
         catch(Exception ex) { }

     if(c == back)
         Display.getDisplay(this).setCurrent(form);

     if(c == read)
     {
         Thread th = new Thread(this);
         th.start();
     }

     if(c == update)
         try{
             Display.getDisplay(this).setCurrent(form3);
         }
         catch(Exception ex)
         {
             ex.printStackTrace();
         }

     if(c == confirmu)
         try{
             recordStore.setRecord(Integer.parseInt(t2.getString()), t3.getString().getBytes(), 0, t3.size());
           Alert a1 = new Alert("Done", "Record Updated",null, null);
            a1.setTimeout(1000);
            Display.getDisplay(this).setCurrent(a1);
         }
         catch(Exception ex)
         {
             ex.printStackTrace();
         }
     if(c == delete)
             try
             {
                 Display.getDisplay(this).setCurrent(form2);
             }
             catch(Exception ex)
             {
                 ex.printStackTrace();
             }

     if(c == confirmd)
         try
         {
             recordStore.deleteRecord(Integer.parseInt(this.t1.getString()));
             Display.getDisplay(this).setCurrent(form2);
             Alert a2 = new Alert("Done", "Record Deleted",null, null);
            a2.setTimeout(1000);
            Display.getDisplay(this).setCurrent(a2);
         }
         catch(Exception ex)
         {
             ex.printStackTrace();
         }
 }

 public void run()
 {
     byte byteInputData[] = new byte[1];
     int length = 0;
     try
     {
         for(int x = 0; x <= recordStore.getNumRecords(); x++)
             try
             {
                 int timeout=1000;
                 if(recordStore.getRecordSize(x) > byteInputData.length)
                     byteInputData = new byte[recordStore.getRecordSize(x)];
                 length = recordStore.getRecord(x, byteInputData, 0);
                 alert = new Alert("Reading","RecordID:-  "+ x + "  " +"Data:-  "+ new String(byteInputData, 0, length), null, AlertType.WARNING);
                 alert.setTimeout(timeout);
                 Display.getDisplay(this).setCurrent(alert);
                 Thread.sleep(timeout);
             }
             catch(Exception error) { }
        
     }
     catch(RecordStoreNotOpenException ex)
     {
         ex.printStackTrace();
     }
  Display.getDisplay(this).setCurrent(form);
 }

}

Thursday, August 4, 2011

Bluetooth in J2ME :- Simple chat application

0 comments
In previous tutorial , we learned about Bluetooth Device Discovery.

In this tutorial we will learn ,how to make simple bluetooth connection .In this we will implement the code in which approval for connection is not required by the sender. Reciever automatically recieves the sent text.


Here is the code for the Bluetooth Chat:-(2 .java files )

Client.java:-


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

/*
 * @author Vaibhav
 */
public class Client extends MIDlet implements CommandListener,DiscoveryListener,Runnable {

   
    private Display display;
    public List devicelist;
    private final List deviceList;
    public DiscoveryAgent agent;
    public String deviceName,address;
    private Command Refresh,connect,end,Exit;
    private String s,url;
    private Alert dialog1;
    private StreamConnection conn;
    private Server b;
    private DataOutputStream dos;
    private String[][] array[][] ;
    Thread t;
  
  
    public Form ChatForm = new Form("chat window");
    private Command send,exit;
    private TextField textfield;
    private String sendmsg;
 
   
    public Client()
    {
        deviceList = new List("List of Devices",List.IMPLICIT);
        Exit= new Command("Exit",Command.EXIT, 0);
        connect = new Command("connect",Command.SCREEN, 1);
        Refresh = new Command("Refresh",Command.SCREEN, 1);
        end = new Command("End",Command.EXIT, 1);
        deviceList.addCommand(Exit);
        deviceList.addCommand(connect);
        deviceList.addCommand(Refresh);
        deviceList.setCommandListener(this);
        Display.getDisplay(this).setCurrent(deviceList);
     
        t = new Thread(this);
    }
    public void startApp() throws MIDletStateChangeException {
        try {
            b=new Server(this);
            getChatForm();
            deviceList.deleteAll();
            LocalDevice local = LocalDevice.getLocalDevice();
            address = local.getBluetoothAddress();
            agent = local.getDiscoveryAgent();
            
        } catch (BluetoothStateException ex) {
            throw new MIDletStateChangeException("Unable to retrieve local Bluetooth device.");
        }
      
            }
   

    public void pauseApp() {

    }
    public void clear() throws IOException
    {
         b.destroy();
    }

    public void destroyApp(boolean unconditional) throws MIDletStateChangeException{
     
    notifyDestroyed();
    }

    public void commandAction(Command c, Displayable d) {
       if(c==Exit)
        {
         try {
                dos.writeUTF("eof");
             } catch (IOException ex) {
                  ex.printStackTrace();
                }
                notifyDestroyed();
         }

       if(c==Refresh){
            try {
                try {
                agent.startInquiry(DiscoveryAgent.GIAC, this);
                dialog1 = new Alert("Searching","Please Wait ,Searching devices",null,AlertType.INFO);
                dialog1.setTimeout(1000);
                Display.getDisplay(this).setCurrent(dialog1);
            } catch (BluetoothStateException e) {
                    throw new MIDletStateChangeException("Unable to start the inquiry");
}
            } catch (MIDletStateChangeException ex) {
                ex.printStackTrace();
            }
       }

       if(c==connect){
           Display.getDisplay(this).setCurrent(ChatForm);
         
           s= deviceList.getString(deviceList.getSelectedIndex());
           url =  "btspp://"+ s + ":" + "1" ;
           System.out.println(url);
           t.start();
       }
       if(c==send){
           sendmsg =  textfield.getString() ;
           textfield.setString("");
           this.ChatForm.append("\n"+"ME: "+sendmsg);
       try {
             dos.writeUTF(address+sendmsg);
           } catch (IOException ex) {
                ex.printStackTrace();
              }            
       }
 }

    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
         try {
            String deviceaddress = btDevice.getBluetoothAddress();
            String address = btDevice.getFriendlyName(true);
            deviceList.insert(0, deviceaddress , null);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
       
    }

    public void serviceSearchCompleted(int transID, int respCode) {
       
    }

    public void inquiryCompleted(int discType) {
        Alert dialog = null;
        if (discType != DiscoveryListener.INQUIRY_COMPLETED) {
            dialog = new Alert("Bluetooth Error","The inquiry failed to complete normally",null, AlertType.ERROR);
          }
         else {
              dialog = new Alert("Inquiry Completed","The inquiry completed normally", null,AlertType.INFO);
              }
              dialog.setTimeout(500);
              Display.getDisplay(this).setCurrent(dialog);
                                
    }

    public void run() {
        try {
               conn = (StreamConnection) Connector.open(url);        
               dos = conn.openDataOutputStream();     
            } catch (Exception ex) {
               System.out.println("here");
                ex.printStackTrace();
           }
        }
     public void setText(String s)
     {
        this.ChatForm.append("\n"+"Friend: "+s);
      }

    public void getChatForm()
    {
        textfield = new TextField("type text ","",50,TextField.ANY);
         exit = new Command ("Exit", Command.EXIT,1);
         send = new Command ("send",Command.OK,1);
         ChatForm.append(textfield);
         ChatForm.append("---------------------");
         ChatForm.addCommand(exit);
         ChatForm.addCommand(send);
         ChatForm.setCommandListener(this);
  }
    void setUp(String url1)
    {
       try{
        url =  "btspp://"+ url1 + ":" + "1" ;
        t.start();
       }catch(Exception e){
       e.printStackTrace();
       }
    }
}

-------------------------------------------------------------------------------------------------------------------


Server.java:-



import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.Display;

/**
 * @author Vaibhav
 */
public class Server implements Runnable   {

    public DataInputStream dis;
    private StreamConnection con;
    public boolean listening = false;
    private Client Client;
    StreamConnectionNotifier notifier = null ;
    String msg,msg1,msg2;
    int count;
    public Server(Client Client)
    {
      this.Client = Client;
      count=0;
       try{
         Thread t = new Thread(this);
         t.start();
        }
       catch(Exception e)
        {}
   }
   public void run() {
          try {
    // retrieve the local Bluetooth device object
    LocalDevice localDevice = LocalDevice.getLocalDevice();
    // retrieve the Bluetooth address of the local device
    String address = localDevice.getBluetoothAddress();
    // retrieve the name of the local Bluetooth device
    String deviceName = localDevice.getFriendlyName();
    System.out.println(address+"   "+deviceName);
    DiscoveryAgent agent =localDevice.getDiscoveryAgent();
    localDevice.setDiscoverable(DiscoveryAgent.GIAC);
     UUID uuid = new UUID(0x0009);
    String url = "btspp://localhost:" + uuid + ";name=" + deviceName + ";" +
                  "authenticate=true"  ;
    notifier = (StreamConnectionNotifier) Connector.open(url);
    con =notifier.acceptAndOpen();
    dis =con.openDataInputStream();
    listening = true;
    setChat();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
 }
   public  void  destroy() throws IOException
    {
     notifier.close();
    listening = false;
    }
   public void  setChat()
    {
     try{
         while(listening)
          {
            msg = dis.readUTF();
            msg1=msg.substring(0,12);
            msg2=msg.substring(12);
            if(count==0)
            {
            Client.setUp(msg1);
            }
            count=1;
             try{
                 if(!msg2.equals("eof")){
                    Display.getDisplay(Client).setCurrent(Client.ChatForm);
                    System.out.println(msg2);
                    Client.setText(msg2);
                   }
                    else
                     listening=false;
             }
              catch(Exception e)
                        {
                            e.printStackTrace();
                        }
              }
       }
            catch(Exception ex)
                      {
                          ex.printStackTrace();
                      }
       
    }
}

------------------------------------------------------------------------------------------------------------------

Now first we will go through the Midlet Client.java
As you can see ,it is almost similar to the previous tutorial code ,device discovery.
When constructor client runs ,it initialises the Displayable item.
StartApp()  meanwhile creates the instance of Server class and calls its constructor.
It also calls getChatForm() which defined the display of chatform as you can see in the getChatForm function code.
Rest of the command is same as it was in device discovery.

Now when refresh button is pressed, then the mobile searches for bletooth device through startInquiry(0 as explained in previous tutorial.
After we have got a list of devices and then we press connect on selected address then the commandaction of connect comes into play.
It checks for the selected device , gets its address and creates a URL as visible in following statements.

 s= deviceList.getString(deviceList.getSelectedIndex());
           url =  "btspp://"+ s + ":" + "1" ;

Then the Thread is started.

The run function is excecuted , in which
conn = (StreamConnection) Connector.open(url);        
               dos = conn.openDataOutputStream();
commands creates a stream connection to the url created in connect command.

Then a dataoutput stream is opened to send data.
Now when send command is given ,
sendmsg =  textfield.getString() ; gets the string entered.

This append the sent message to sender's screen.
this.ChatForm.append("\n"+"ME: "+sendmsg);

Then this command sends the data and address of the sending mobile through outputstreamconnection.
dos.writeUTF(address+sendmsg);
This concludes client side coding.


Now in server class,as soon as its instance is created by client ,its constructor runs.
this.Client = Client;
Above command hepls the class to locate its parent class.
Then it starts the thread.
The run function on server is executed.

This statement  retrieves the local Bluetooth device object
    LocalDevice localDevice = LocalDevice.getLocalDevice()
;
    Then it retrieve the Bluetooth address of the local device
    String address = localDevice.getBluetoothAddress();

    This retrieve the name of the local Bluetooth device
    String deviceName = localDevice.getFriendlyName();

    This creates a discoveryagent.
    DiscoveryAgent agent =localDevice.getDiscoveryAgent();


This sets the device as discoverable.Check for other options available for hiding the device.
    localDevice.setDiscoverable(DiscoveryAgent.GIAC);
     UUID uuid = new UUID(0x0009);
    String url = "btspp://localhost:" + uuid + ";name=" + deviceName + ";" +
                  "authenticate=true"  ;

above 2 statements prepares the Connection URL.
This statement creates the connection notifier.
notifier = (StreamConnectionNotifier) Connector.open(url);
Now the essence of our coding was that it didn't required approval .here is the piece of code which decides it.
con =notifier.acceptAndOpen();
It automatically accepts incoming connection and opens stream.
dis =con.openDataInputStream();
Then setchat function is executed.

msg = dis.readUTF();
            msg1=msg.substring(0,12);
            msg2=msg.substring(12);
Above coding is done to seperate address and the text so that address can be used to connect back to the sender and data is displayed on chatform (however setText function of client is  used for this purpose.)


However when count is 0 ,it calls setUp function. This is done when the reciever recieves data for the first time .This is done so that it can connect back to the sender to reply. However when reciever sends back 2nd time ,the count increses to more than 0 and it skips this part.
Finally setUp function of client just prepares the connection URL for server to connect back.

This concludes our tutorial .
In next tutorial we'll learn request/response connection in which reciever can accept /reject the connection.











Friday, July 29, 2011

Bluetooth in J2ME : Bluetooth Device Discovery

0 comments
In this tutorial we will learn about Mobile Bluetooth and its application using J2ME.
First of all , for all those who give more importance to underlying protocols , i found a beautiful explaination on this site:-
http://developers.sun.com/mobility/midp/articles/bluetooth1

Now after you know basic protocol structure (However its not mandatory to create application) , we can start with the modules we have to follow.

In Bluetooth programming wehave following jobs in our hand:-
  • Device Discovery
  • Request/Response for Connection
  • Sending Data 
  • Recieving Data
In this particular tutorial we'll be limiting ourselves to device discovery only.
Rest we'll cover in subsequent posts.
First of all   we should know that we will use(rather the only one available) the java API  JSR82.

For information regarding device compatibility , minimum requirements , requirements for application development and lots more you can go through this link:-
http://developers.sun.com/mobility/midp/articles/bluetooth2

Now let us first go through the code :-

----------------------------------------------------------------------------------------------
import java.io.IOException;
import javax.bluetooth.*;
import javax.bluetooth.DiscoveryListener;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;


/**
* @author Vaibhav
*/
public class discover_device extends MIDlet implements CommandListener,DiscoveryListener {

private final List deviceList;
private final Command Exit,Refresh;
private String deviceName;
private DiscoveryAgent agent;
private Alert dialog;

public discover_device()
{
 deviceList = new List("List of Devices",List.IMPLICIT);
 Exit= new Command("Exit",Command.EXIT, 0);
 Refresh = new Command("Refresh",Command.SCREEN, 1);
  deviceList.addCommand(Exit);
 deviceList.addCommand(Refresh);
 deviceList.setCommandListener(this);
 Display.getDisplay(this).setCurrent(deviceList);
}

public void startApp() {
try {
deviceList.deleteAll();
LocalDevice local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);
deviceName = local.getFriendlyName();
agent = local.getDiscoveryAgent();
}
catch (BluetoothStateException ex) {
ex.printStackTrace();
}
try {
 agent.startInquiry(DiscoveryAgent.GIAC, this);
}
catch (BluetoothStateException ex) {
ex.printStackTrace();
}
}

public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if(c==Exit)
{
this.destroyApp(true);
notifyDestroyed();
}
if(c==Refresh){
this.startApp();
}
}

public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
String deviceaddress = null;
try {
deviceaddress = btDevice.getBluetoothAddress();//btDevice.getFriendlyName(true);
} catch (Exception ex) {
ex.printStackTrace();
}
deviceList.insert(0, deviceaddress , null);
}

public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
 throw new UnsupportedOperationException("Not supported yet.");
}

 public void serviceSearchCompleted(int transID, int respCode) {
        throw new UnsupportedOperationException("Not supported yet.");
    }




public void inquiryCompleted(int discType) {
        Alert dialog = null;
        if (discType != DiscoveryListener.INQUIRY_COMPLETED) {
            dialog = new Alert("Bluetooth Error","The inquiry failed to complete normally",null, AlertType.ERROR);
          }
         else {
              dialog = new Alert("Inquiry Completed","The inquiry completed normally", null,AlertType.INFO);
              }
              dialog.setTimeout(500);
              Display.getDisplay(this).setCurrent(dialog);

    }
}

---------------------------------------------------------------------------------------------------------

First of all we create a list(Display item) on which we will be displaying the searched device (name or address) and on that same list we will add the command to search and exit.
This will be our first display item on starting the application.
Then the control goes to startApp() function .
The very first command deviceList.deleteAll(); deletes all devices from previous search.

LocalDevice local = LocalDevice.getLocalDevice();
This command gets the local bluetooth device.
local.setDiscoverable(DiscoveryAgent.GIAC);
This command allows the device to be discovered by others.
However using local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
we can hide our bluetooth (not visible to others but others are visible to us)

deviceName = local.getFriendlyName();
This gives us the device name.

agent = local.getDiscoveryAgent();
This sets a discovery agent for bluetooth enquiry.

agent.startInquiry(DiscoveryAgent.GIAC, this);
This is the main statement which starts searching for devices (being a critical command ,its being put into try catch).
Then after inquiry is complete ,then inquiryCompleted() is executed ,which displays whether inquiry is completed successfully or not.
Finally deviceDiscovered() comes to action setting all the display of device discovered on the list.
You can choose between name or address of device to be displayed on list by choosing between these tho statements
deviceaddress = btDevice.getBluetoothAddress();
deviceaddress= btDevice.getFriendlyName(true);
The other one is commented in code.


This Completes out tutorial on Bluetooth device discovery. We'll learn about connection set-up in subsequent part.

Monday, May 16, 2011

To avoid potential deadlock, operations that may block, such as networking, should be performed in a different thread than the commandAction() handler.

2 comments

This type of runtime errors occur due to potential deadlock situations.
I bet you might have faced it a lot if you copy codes from famous J2ME tutorial sites.(even i did)
These occurs when you do critical operations such as networking video,audio or image capture etc. inside commandAction.
The best solution for it is to just ad the trouble creating code to a new thread.
Let me show how.Let us take a sample code:-

import xyz;

class sample extends MIDlet implements CommandListener
{
 Command  start; = new Command("Start", Command.OK, 1);

 public Midlet()
 {
  start = new Command("Start", Command.EXIT, 1);
 }
 public void commandAction(Command command, Displayable displayable)
 {
  if (command == start)
  {
      potential deadlock statements
      potential deadlock statements
      potential deadlock statements
  }
 }
}

Here simply make the following changes:-


import xyz;


class sample extends MIDlet implements CommandListener,Runnable

{
Command  start; = new Command("Start", Command.OK, 1);


public Midlet()
{
start = new Command("Start", Command.EXIT, 1);

}
public void commandAction(Command command, Displayable displayable)
{
if (command == start)
{
     Thread t=new Thread(this);
     t.start();
 }

}
   public void run()
   {
       potential deadlock statements
      potential deadlock statements
      potential deadlock statements
    }


}

This will surely solve your problem

customised by Vaibhav