Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static fields in Activity classes guaranteed to outlive a create/destroy cycle?

I frequently run into the problem that I have to preserve state between several invocations of an activity (i.e. going through several onCreate()/onDelete() cycles). Unfortunately, Android's support for doing that is really poor.

As an easy way to preserve state, I thought that since the class is only loaded once by the class loader, that it would be safe to store temporary data that's shared between several instances of an activity in a static Bundle field.

However, occasionally, when instance A creates the static bundle and stores data in it, then gets destroyed, and instance B tries to read from it, the static field is suddenly NULL.

Doesn't that mean that the class had been removed and reloaded by the classloader while the activity was going through a create/destroy cycle? How else could a static field suddenly become NULL when it was referencing an object before?

like image 843
Matthias Avatar asked Oct 28 '09 10:10

Matthias


People also ask

Can fields be static?

Third, the Java field can be declared static . In Java, static fields belongs to the class, not instances of the class. Thus, all instances of any class will access the same static field variable. A non-static field value can be different for every object (instance) of a class.

What is onCreate Method in Android?

onCreate is used to start an activity. super is used to call the parent class constructor. setContentView is used to set the xml.

Do not place Android context classes in static fields is a memory leak Java?

The solution itself is fairly simple: Do not place context fields in static instances, whether that of a wrapping class or declaring it static directly. And the solution to the warning is simple: don't place the field statically. In your case, pass the context as an instance to the method.

What is activity class in Java?

An activity represents a single screen with a user interface just like window or frame of Java. Android activity is the subclass of ContextThemeWrapper class.


2 Answers

The first part of this answer is really old -- see below for the right way to do it

You can use the Application object to store application persistent objects. This Android FAQ talks about this problem as well.

Something like this:

public class MyApplication extends Application{
    private String thing = null;

    public String getThing(){
        return thing;
    }

    public void setThing( String thing ){
        this.thing = thing;
    }
}

public class MyActivity extends Activity {
    private MyApplication app;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        app = ((MyApplication)getApplication());

        String thing = app.getThing();
    }
}

The right way:

When this answer was first written, the documentation for the Activity lifecycle was not as good as it is now. Reading Saving Activity State section on the Activity document helps us understand how Android wants us to save state. Essentially, there are two circumstances under which your activity starts: (1) as a new activity and (2) because of a configuration change or when it's recreated after being destroyed due to memory pressure. When your activity starts because it's a new activity, then saveInstanceState is null. It's not null otherwise. If it's null, then your activity should initialize itself from scratch. Fragments are very similar to Activities, and I covered this concept in detail for my AnDevCon-14 slide deck. You can also take a look at the sample code for my AnDevCon-14 presentation for more details.

Reworking my previous example would look something like the code below. I do change the semantics a bit -- in this second version I assume the string thing is specific to the activity within a specific android task, in the previous example it's ambiguous. If you do want to keep the same data around for multiple android tasks, then using either the Application object or another singleton is still your best bet.

public class MyActivity extends Activity {
    private static final String THING = "THING";

    private String thing;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState==null) {
            // First time here (since we last backed out at least)
            thing = initializeThing(); // somehow we init it
        } else {
            // Rehydrate this new instance of the Activity
            thing = savedInstanceState.getString(THING);
        }

        String thing = app.getThing();
    }

    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(THING, thing);
    }
}
like image 163
JohnnyLambada Avatar answered Oct 04 '22 22:10

JohnnyLambada


The other, also evil, way to keep static data is to have you activity spin up a singleton class. This singleton would keep a static reference to itself.

class EvilSingleton{
    private static EvilSingleton instance;

    //put your data as non static variables here

    public static EvilSingleton getInstance()
    {
        if(instance == null)
            instance = new EvilSingleton();
        return instance;
    }
}

In the onCreate() method of your activity you can access/build the singleton and any data you might need. That way, your activity or application can get destroyed or recreated any number of times and as long as your process' memory space is preserved you should be ok.

This is an evil subversive hack, so no promises ;-)

like image 31
haseman Avatar answered Oct 04 '22 22:10

haseman