views:

1777

answers:

3

How can I create global variable keep remain values around the life cycle of the application regardless which activity running..

+1  A: 

Hi
You can use a Singleton Pattern. Like this:


package com.ramps;

public class MyProperties {
    private static MyProperties mInstance= null;

    public int someValueIWantToKeep;

    protected MyProperties(){}

    public static synchronized MyProperties getInstance(){
     if(null == mInstance){
      mInstance = new MyProperties();
     }
     return mInstance;
    }
}

In your application you can access your singleton in this way:

MyProperties.getInstance().someValueIWantToKeep
Ramps
What if activity paused and user started another application and during that memeory was low thats why android removed this static object when user resume application and found this static reference null ???
Faisal khan
Good point. You could use onSaveInstanceState(Bundle) from one of your activities to save the state of your singleton. Another solution would be to implement persistent DAO basing on SharedPreferences. In this case your data would be always kept in persistent memory.
Ramps
+9  A: 

You can extend the base android.app.Application class and add member variables like so:

public class MyApplication extends Application {

    private String someVariable;

    public String getSomeVariable() {
        return someVariable;
    }

    public void setSomeVariable(String someVariable) {
        this.someVariable = someVariable;
    }
}

In your android manifest you must declare the class implementing android.app.Application:

<application android:name="MyApplication" android:icon="@drawable/icon" android:label="@string/app_name">

Then in your activities you can get and set the variable like so:

// set
((MyApplication) this.getApplication()).setSomeVariable("foo");

// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
Jeff Gilfelt
awesome help, i really applicate.
Faisal khan
A: 

You could use application preferences. They are accessible from any activity or piece of code as long as you pass on the Context object, and they are private to the application that uses them, so you don't need to worry about exposing application specific values, unless you deal with routed devices. Even so, you could use hashing or encryption schemes to save the values. Also, these preferences are stored from an application run to the next. Here is some code examples that you can look at.

r1k0