tags:

views:

282

answers:

2

hi,

i have a midlet which has got a static variable. i need to keep the record of all the instances created in this variable. but it does not work like static variable. my code segments look like this. i am running this midlet on sun wireless toolkit 2.5.5. i can create many objects of same midlet from that toolkit but still my counter shows only 1.

public class SMS extends MIDlet implements CommandListener {

private Display display; private TextField userID, password ; public static int counter ;

public SMS() {

  userID = new TextField("LoginID:", "", 10, TextField.ANY);
  password = new TextField("Password:", "", 10, TextField.PASSWORD);
  counter++;

}

public void startApp() {

  display = Display.getDisplay(this);
  loginForm.append(userID);
  loginForm.append(password);
  loginForm.addCommand(cancel);
  loginForm.addCommand(login);
  loginForm.setCommandListener(this);
  display.setCurrent(loginForm);

public void commandAction(Command c, Displayable d) {

 String label = c.getLabel();
 System.out.println("Total Instances"+counter);

everytime, counter shows only 1 object created. please, help me out

+1  A: 

Your MIDlet is only instantiated once. Kind of.

The MIDP runtime will probably not allow you to launch the same MIDlet twice as long as it is already running.

If you exit the MIDlet, counter goes back to 0 because it is still a in-RAM value and the Java Virtual Machine process is terminated.

On some Nokia series40 phones, the JVM process is never terminated so you could use this to show how many times the MIDlet was created since the last time the phone was switched on.

Static variables are stored in a Class object in the JVM memory. You need to understand class loading (and the usual lack of support for class unloading in J2ME) to figure out what you can store in static variable.

I would suggest moving counter++; to startApp() as it could be called everytime the MIDlet is brought to the foreground.

That would also allow you to store counter in an RMS record for additional accuracy.

QuickRecipesOnSymbianOS
A: 

The only system I've seen that allows static variables to remain between 'invocations' of an application is Android. I've never once seen a J2ME device that maintains static data between invocations of a MIDlet. However, MIDlets within a MIDlet suite can share static data, as described here, while at least one of them is running.

If you want to maintain data between invocations of a MIDlet, you need to use the Record Store APIs in javax.microedition.rms, which provide access to a persistent store.

LongSteve