How does a MIDlet call a static variable?

I have a midlet that has a static variable. I need to keep a record of all instances created in this variable. but it doesn't work like a static variable. my code segments look like this. I am running this midlet on sunscreen 2.5.5 toolkit. I can create many objects of the same midlet from this toolkit, but still my counter only shows 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);

      

each time, the counter shows only 1 created object.

+2


source to share


2 answers


Your MIDlet is only created once. View.

The MIDP runtime will probably prevent you from running the same MIDlet twice while it's already running.

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

On some Nokia series40 phones, the JVM process never ends, so you can use this to show how many times a MIDlet has been created since the phone was last turned on.



Static variables are stored in a Class object in 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 a static variable.

I would suggest moving counter++;

to startApp()

, as this could be called every time the MIDlet is brought to the front.

This will also allow you to store the counter in an RMS record for added precision.

+1


source


The only system I've seen that allows static variables to stay between "invocations" of an application is Android. I've never seen a J2ME device that maintains static data between MIDlet calls. However, a MIDlet in a MIDlet suite can share static data as described here , even though at least one of them is running.



If you want to maintain data between MIDlet calls, you need to use the Record Store API in javax.microedition.rms, which provide persistent storage access.

+1


source







All Articles