简体   繁体   中英

How can I implement session variables in J2ME?

Is it possible to use session in J2me? I am trying to develop a Blackberry application. I want to get some text from a class(page) and use in another class(page). May be something like the we do in app.net as:

Class1
{
    session("myVariable") = Textbox.Text;
}

//a new class
Class2
{
    TextBox2.Text = session("myVariable").toString();
}

I will really appreciate for any type of help.

You can have a third class where you store such 'global' variables. You can make these variables public and static; though this can lead to tightly coupled code.

public class GlobalVariables
{
    public static string MyVariable = "empty";
}

Then you can do...

GlobalVariables.MyVariable = Textbox.Text;

...and...

TextBox2.Text = GlobalVariables.MyVariable;

...anywhere in your code. While this would tend to be frowned upon in usual circumstances it can be useful when trying to write minimal, fast code to run on limited devices.

Another tip is to have a reset-method in GlobalVariables to reset all the static values back to their defaults in case the user wants to reset the app from within the app. Also, if this is the only place you will store all your per-session variables you can add RMS save and load methods in here to keep it all in one place.

Again, it's not the best way of doing things... but it is simple.

When I first saw your question I thought it was going to be about HTTP sessions, but it looks like you're just after a way of storing state in your application.

There are a number of ways to do this. Some things to consider:

  • Do you need to persist the session data (or perhaps some of it) between runs of your application?
  • Is the set of session variables fixed, or can it vary?
  • Are all variables 'stringy' or are some numeric?

A simple implementation might be an instance of Hashtable in a class with public static methods to get and set variables by calling the Hashtable put() and get() methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM