Alex Rivera | Logout

How to declare global variables in Android?

Asked 2009-04-02T01:54:30.160
608

I am creating an application which requires login. I created the main and the login activity.

In the main activity onCreate method I added the following condition:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ...
        
        loadSettings();
        if(strSessionString == null)
        {
            login();
        }
        ...
    }

The onActivityResult method which is executed when the login form terminates looks like this:

    @Override
    public void onActivityResult(int requestCode,
                                 int resultCode,
                                 Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode)
        {
            case(SHOW_SUBACTICITY_LOGIN):
            {
                if(resultCode == Activity.RESULT_OK)
                {
                    
                    strSessionString = data.getStringExtra(Login.SESSIONSTRING);
                    connectionAvailable = true;
                    strUsername = data.getStringExtra(Login.USERNAME);
                }
            }
        }

The problem is the login form sometimes appears twice (the login() method is called twice) and also when the phone keyboard slides the login form appears again, and I guess the problem is the variable strSessionString.

Does anyone know how to set the variable global in order to avoid login form appearing after the user already successfully authenticates?

Edit
Report

2 Answers

4

If some variables are stored in sqlite and you must use them in most activities in your app. then Application maybe the best way to achieve it. Query the variables from database when application started and store them in a field. Then you can use these variables in your activities.

So find the right way, and there is no best way.

answered 2011-04-20T07:32:17.910
1

you can use Intents , Sqlite , or Shared Preferences . When it comes to the media storage, like documents , photos , and videos, you may create the new files instead.

answered 2013-07-16T01:35:07.333

Your Answer