PAGES

Showing posts with label J2ME Tutorials. Show all posts
Showing posts with label J2ME Tutorials. Show all posts

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

Sunday, May 15, 2011

HTTP Connection in J2ME

2 comments
 HTTP is a request-response protocol in which the parameters of request must be set before the request is sent.
 The connection exists in one of three states:

    * Setup, in which the request parameters can be set
    * Connected, in which request parameters have been sent and the response is expected
    * Closed, the final state, in which the HTTP connection as been terminated

To read a URL we can use StreamConnection.No HTTP specific behavior is needed or used.
Connector.open is used to open URL and a StreamConnection is returned.
First we open an output stream by the openOutputStream or openDataOutputStream  methods.
Then we send the get request along with the HTML format.
When the output stream is flushed via the OutputStream.flush or DataOutputStream.flush  methods,
the request parameters MUST be sent along with any data written to the stream.
When an output stream is closed via the OutputStream.close or DataOutputStream.close  methods,
the connection enters the Connected state.
The transition to Closed state from any other state is caused by the close method and the closing all
of the streams that were opened from the connection.
From the StreamConnection the InputStream is opened.
It is used to read every character until end of file (-1). If an exception is thrown the connection and stream are closed.

Here note that you have to give standard form URL like "http://www.sitename.com"
Ex:- "http://www.Google.com" ,"http://www.yahoo.com"
However you can also check it by running a localhost server like apache and glassfish.
Ex:- For apache server with 8080 port you can use "http://localhost:8080"

I came around many students who doubted whether their IP will work instead of localhost.
The answer is yes ,provided you have put the http connection in firewall exception.
So if your Ip is somewhat 202.12.22.13
then you can use: "http://202.12.22.13:8080" assuming port to be 8080.

One more problem that i faced a lot copying codes from famous j2me tutorial sites is they do all the connection work
in commandAction() itself which gives error
"Connection should be opened in thread other than CommandAction Handler"
So try to create seperate thread for avoiding deadlock and call the thread in commandAction().

Source Code:-


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

public class http extends MIDlet implements CommandListener,Runnable {
  private Command exit, start;
  private Form form;

  public http ()
  {
    exit = new Command("Exit", Command.EXIT, 1);
    start = new Command("Start", Command.EXIT, 1);
    form = new Form("Browse");
    form.addCommand(exit);
    form.addCommand(start);
    form.setCommandListener(this);
  }
  public void startApp() throws MIDletStateChangeException
  {
    Display.getDisplay(this).setCurrent(form);
  }
  public void pauseApp()
  {
  }
  public void destroyApp(boolean unconditional)
  {
  }
  public void commandAction(Command command, Displayable displayable)
  {
    if (command == exit)
    {
      destroyApp(false);
      notifyDestroyed();
    }
    else if (command == start)
    {
        Thread thread1 = new Thread(this);
        thread1.start();
        System.out.println("Thread Started");
    }
  }
  public void run()
          {
   try
      {
       HttpConnection connection = (HttpConnection) Connector.open("http://www.google.com");
       PrintStream output =new PrintStream(connection.openOutputStream() );
       output.println( "GET /my.html HTTP/1.0 \n" );
       output.flush();
       InputStream in = connection.openInputStream();

      //put the code for screen display here given at the end of the post

      int ch;
       while( ( ch = in.read() ) != -1 )
      {
         System.out.print( (char) ch );
       }
    
       in.close();
       output.close();
       connection.close();
     }
      catch( Exception error )
       {
         Alert alert = new Alert("Error", "Cannot access URL.", null, null);
         alert.setTimeout(Alert.FOREVER);
         alert.setType(AlertType.ERROR);
         Display.getDisplay(this).setCurrent(alert);
        }
  }
}


In this code the output will appear on output console of the IDE you are using.
If you want to see the output on mobile screen just add these lines at the location specified in the code(first read the code)
 DataInputStream dataInputStream = new DataInputStream(in);
      int inputChar;
      StringBuffer results = new StringBuffer();
      while ( (inputChar = dataInputStream.read()) != -1)
      {
       results.append((char) inputChar);
      }
    
      // display the page contents on the phone screen
      StringItem resultField = new StringItem(null, results.toString());
      form.append(resultField);


Wednesday, April 6, 2011

RercordStore:-Saving data in mobile

0 comments
In this tutorial we will learn how to save various file types(video ,audio ,images as well as text ) in a recordstore.Now when you go through the code you'll find
byte[] bytestream = t.getString().getBytes();
here t is a textfield.Hence we save text in this case.
If you want to save image or video ,simply convert it to bytes and then replace t.getString().getBytes() by the bytes you just got.


To View tutorial video Online CLICK HERE
(Download and watch for better quality)
To download Click here


SOURCE CODE:-

 Record.JAVA

import java.io.*;
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;


public class Record extends MIDlet implements CommandListener {

    private Form form;
    private TextField t,t1;
    private Command write,read;
    private RecordStore recordStore;

    public Record()
    {
        form = new Form("Record");
        read = new Command("Read", Command.SCREEN, 1);
        write = new Command("Write", Command.SCREEN, 1);
        form.addCommand(write);
        form.addCommand(read);
        form.setCommandListener(this);
        try {
            recordStore = RecordStore.openRecordStore("My record", true);
        }
        catch (Exception ex) {
        }
        t=new TextField("Enter data","",30,TextField.ANY);
        t1=new TextField("Read data","",30,TextField.ANY);
        form.append(t);
        form.append(t1);
    }

    public void startApp() {
        Display.getDisplay(this).setCurrent(form);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        if(c==write)
        {
            try {
                byte[] bytestream = t.getString().getBytes();
                recordStore.addRecord(bytestream, 0, bytestream.length);
            }
            catch (Exception ex) {
            }
        }
        if(c==read)
        {
            try {
                byte[] Data = new byte[recordStore.getRecordSize(1)];
                int length = recordStore.getRecord(1, Data, 0);
                t1.setString(new String(Data, 0,length));
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

Delete and update in recordstore is covered in next tutorial.

Thursday, December 23, 2010

Creating a Camera Appliction in J2ME

1 comments
In this tutorial you will learn to create a simple camera program.For this we will use a canvas class named "VideoCanavas" and call it in our main MIDlet "CameraMidlet".
Here we first make the camera view visible by camera button and then add the capture button to take a snapshot.Also we create a class "Video" inside "CameraMidlet" to capture the picture.
For making camera view visible we have to add a player.In the code the following statement is used for S60 devices to add player :-
player = Manager.createPlayer("capture://video");

For S40 devices replace this line with  :-

player = Manager.createPlayer("capture://image");

Also in this tutorial we have no provision for saving the clicked photo.So everytime you close application  ,image goes off.
For the memory part ,we will use Recordstore ,which we will study in next tutorial and then finally we will join the 2 to make the complete camera program. 

NOTE:- The camera view in S.D.K is not proper as it is just an emulation.Also it shows java.lang.outofmemory exception. This is due to lack of memory in S.D.K's .So better try it on mobile.

To View tutorial video Online CLICK HERE
(Download and watch for better quality)
To download Click here

 SOURCE CODE:-

CameraMidlet.java:-

import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.VideoControl;
import javax.microedition.midlet.*;

public class CameraMidlet extends MIDlet implements CommandListener {
     private Form form;
     private Command exit,camera,capture;
     private Player player;
     private VideoControl videoControl;
     public byte[] raw;
     private Video vid;

     public CameraMidlet()
     {
         form = new Form("Capture Video");
         exit = new Command("Exit", Command.EXIT, 0);
         camera = new Command("Camera", Command.SCREEN, 0);
         form.addCommand(camera);
         form.addCommand(exit);
         form.setCommandListener(this);
         capture = new Command("Capture", Command.SCREEN, 0);
     }
    public void startApp() {
        Display.getDisplay(this).setCurrent(form);
    }
    public void pauseApp() {
    }
    public void destroyApp(boolean unconditional) {
    }
    public void commandAction(Command c, Displayable d) {
         if (c == exit) {
            destroyApp(true);
            notifyDestroyed();
        }
         if (c == camera) {
            showCamera();
        }
         if (c == capture) {
                  try{
            vid = new Video(this);
            vid.start();
           }catch(Exception e)
           {}
         }
    }
    public void showCamera() {
        try {
            player = Manager.createPlayer("capture://video");
            player.realize();
            videoControl = (VideoControl)player.getControl("VideoControl");
            Canvas canvas = new VideoCanvas(this, videoControl);
            canvas.addCommand(capture);
            canvas.setCommandListener(this);
            Display.getDisplay(this).setCurrent(canvas);
            player.start();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    class Video extends Thread {
    CameraMidlet midlet;
    public Video(CameraMidlet midlet) {
            this.midlet = midlet;
        }
    public void run() {
            captureVideo();
        }
     public void captureVideo()
     {
            try {
                raw = videoControl.getSnapshot(null);
                Image  image = Image.createImage(raw, 0, raw.length);
                player.close();
                player = null;
               videoControl = null;
            } catch (MediaException ex) {
                ex.printStackTrace();
            }
     }
    }
}


VideoCanvas.java:-

import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.VideoControl;

public class VideoCanvas extends Canvas {
    private CameraMidlet parent;
    public VideoCanvas(CameraMidlet midlet,VideoControl videoControl) {
        int width = getWidth();
        int height = getHeight();
        this.parent = midlet;
         videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
        try {
            videoControl.setDisplayLocation(2, 2);
            videoControl.setDisplaySize(width - 4, height - 4);
        } catch (MediaException me) {}
        videoControl.setVisible(true);
    }
    protected void paint(Graphics g) {
         int width = getWidth();
        int height = getHeight();
        g.setColor(0x00ff00);
        g.drawRect(0, 0, width - 1, height - 1);
        g.drawRect(1, 1, width - 3, height - 3);
    }
}

Thursday, December 16, 2010

Canvas in J2ME

0 comments
A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user.


An application must subclass(extend) the Canvas class in order to get useful functionality such as creating a custom component. The paint method must be overridden in order to perform custom graphics on the canvas.


To View tutorial video Online CLICK HERE
(Download and watch for better quality)
To download Click here


Lets assume you create function paint(Graphics g).
You can view the list of functions available as well as their syntax ,usage and details can be seen by just typing the g.(g dot) and the list automatically opens up .Just move to required function and its details apppears as well.
Some of the common functions available in canvas are:-


  • public void drawImage(Image img, int x, int y, int anchor)
Draws the specified image by using the anchor point. The image can be drawn in different positions relative to the anchor point by passing the appropriate position constants. See anchor points.
If the source image contains transparent pixels, the corresponding pixels in the destination image must be left untouched. If the source image contains partially transparent pixels, a compositing operation must be performed with the destination pixels, leaving all pixels of the destination image fully opaque.
If img is the same as the destination of this Graphics object, the result is undefined. For copying areas within an Image, copyArea should be used instead.


Parameters:
img - the specified image to be drawn
x - the x coordinate of the anchor point
y - the y coordinate of the anchor point
anchor - the anchor point for positioning the image




  • public void drawString(String str, int x, int y, int anchor)
Draws the specified String using the current font and color. The x,y position is the position of the anchor point. See anchor points.


Parameters:
str - the String to be drawn
x - the x coordinate of the anchor point
y - the y coordinate of the anchor point
anchor - the anchor point for positioning the text


  • public void fillRect(int x, int y, int width, int height)
Fills the specified rectangle with the current color. If either width or height is zero or less, nothing is drawn.


Parameters:
x - the x coordinate of the rectangle to be filled
y - the y coordinate of the rectangle to be filled
width - the width of the rectangle to be filled
height - the height of the rectangle to be filled


  • public void setColor(int red, int green, int blue)
Sets the current color to the specified RGB values. All subsequent rendering operations will use this specified color.


Parameters:
red - the red component of the color being set in range 0-255
green - the green component of the color being set in range 0-255
blue - the blue component of the color being set in range 0-255


  • public int getColor()
Gets the current color.


  • public void setFont(Font font)
Sets the font for all subsequent text rendering operations. If font is null, it is equivalent to setFont(Font.getDefaultFont()).


  • public void drawRect(int x, int y, int width, int height)
Draws the outline of the specified rectangle using the current color and stroke style. The resulting rectangle will cover an area (width + 1) pixels wide by (height + 1) pixels tall. If either width or height is less than zero, nothing is drawn.


Parameters:
x - the x coordinate of the rectangle to be drawn
y - the y coordinate of the rectangle to be drawn
width - the width of the rectangle to be drawn
height - the height of the rectangle to be drawn


  • public void translate(int x, int y)
Translates the origin of the graphics context to the point (x, y) in the current coordinate system. All coordinates used in subsequent rendering operations on this graphics context will be relative to this new origin.
The effect of calls to translate() are cumulative. For example, calling translate(1, 2) and then translate(3, 4) results in a translation of (4, 6).






CODE:-


import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;




public class Midlet1 extends MIDlet {


    Canvas1 c1=new Canvas1();
    public void startApp() {
        Display.getDisplay(this).setCurrent(c1);
        c1.repaint();
    }


    public void pauseApp() {
    }


    public void destroyApp(boolean unconditional) {
    }
}
class Canvas1 extends Canvas
{


    protected void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
        g.drawString("Hello",10 ,30, 20);
        g.drawRect(40, 40, width-80, height-80);
        g.setColor(220, 0, 0);
        g.fillRect(40, 40, width-80, height-80);
    }
}

                                                  Next Tutorial:-  Canvas Cont.(Simple game)

Tuesday, October 26, 2010

Video Player in J2ME

2 comments
 In this tutorial we will learn how to create a simple Video player in J2ME.
Instead of creating a brand new code lets reuse the code we made in previous tutorial "J2MEAudioPlayer".             
Click here to go to previous tutorial.
However i found 1 limitation that the video length should be limited if we are viewing it offline(not directly from internet but saved video).So in this case i have reduced number of videos to 2 .You may increase the count if your SDK supports it or videos are less than 150 kb.
Download these sample videos to src folder of your project.
1.mpg 
2.mpg  


NOTE:- CLICK ON ARROW KEYS INSIDE VIDEO TO VIEW NEXT FRAME
To View tutorial video Online CLICK HERE
(Download and watch for better quality)

To download Click here



Source Code:-



import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;


public class VideoPlayer extends MIDlet implements CommandListener ,ItemStateListener ,PlayerListener  {


    public String[] elements ={"1","2"};
    public List list =new List("Select Audio File", List.IMPLICIT, elements,null);
    public StringItem si,time;
    private Gauge gauge = new Gauge("Volume: 50", true, 100, 50);
    private VolumeControl volume;
    private Form volume1 =new Form("Adjust volume");

    public Form form = new Form("VideoPlayer");
    private Command Play =new Command("Play",Command.SCREEN,1);
    private Command exitCommand = new Command("Exit", Command.EXIT, 1);
    private Command vol =new Command("Volume",Command.SCREEN,1);
    private Command back =new Command("back",Command.BACK,2);
    private Command pause =new Command("Pause",Command.SCREEN,1);
    private Command Resume =new Command("Resume",Command.SCREEN,1);

    private Player player;


    public VideoPlayer()
    {
    list.addCommand(Play);
    list.addCommand(exitCommand);
    list.setCommandListener(this);
    form.addCommand(pause);
    form.addCommand(Resume);
    form.addCommand(vol);
    form.addCommand(back);
    form.setCommandListener(this);
    volume1.append(gauge);
    volume1.addCommand(back);
    volume1.setItemStateListener(this);
    volume1.setCommandListener(this);

    }
    public void startApp() {
        Display.getDisplay(this).setCurrent(list);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
       if (c == exitCommand)
       {
       cleanUp();
       notifyDestroyed();
       return;
       }
       if (c==Play)
       {
           String s=list.getString(list.getSelectedIndex());
           s="/"+s+".mpg";
           si=new StringItem("Playing",s);
           playMedia(s);
           form.append(si);
          }
       if(c==vol)
       {
           Display.getDisplay(this).setCurrent(volume1);
       }
       if((c==back)&&(d==form))
       {
           try
        {
            player.stop();
        }
        catch (Exception e)
        {
        }
           form.deleteAll();
           cleanUp();
           Display.getDisplay(this).setCurrent(list);
       }
       if((c==back)&&(d==volume1))
       {
           Display.getDisplay(this).setCurrent(form);
       }
           if(c==pause)
       {
        try
        {
            player.stop();
        }
        catch (Exception e)
        {
        }
       }
        if(c==Resume)
       {
         try {
         player.start();
         } catch (Exception e) {
         }
       }
    }
    public void cleanUp() {
    if (player != null) {
      player.close();
      player = null;
    }
  }

     public void playMedia(String locator)
     {
         try{
             player = Manager.createPlayer(getClass().getResourceAsStream(locator),"video/mpeg");
             player.realize();
             player.addPlayerListener(this);
             volume = (VolumeControl) player.getControl("VolumeControl");
             volume.setLevel(70);
             gauge.setValue(volume.getLevel());
             gauge.setLabel("Volume: " + volume.getLevel());
             player.setLoopCount(2);
             float t= player.getMediaTime();
             String c=String.valueOf(t);
             time=new StringItem("Time",c);
             form.append(time);
             player.start();
         }
         catch (Exception e) {
             e.printStackTrace();
         }
     }

    public void itemStateChanged(Item item) {
            volume.setLevel(gauge.getValue());
            gauge.setLabel("Volume: " + volume.getLevel());
    }

   public void playerUpdate(Player player, String event, Object eventData) {
    if(event.equals(PlayerListener.STARTED) ) {
      VideoControl vc = (VideoControl)player.getControl("VideoControl");
        Item videoDisp = (Item)vc.initDisplayMode(vc.USE_GUI_PRIMITIVE, null);
        form.append(videoDisp);


      Display.getDisplay(this).setCurrent(form);
    } else if(event.equals(PlayerListener.CLOSED)) {
      form.deleteAll();
    }
  }
}
customised by Vaibhav