Alex Rivera | Logout

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

Asked 2009-10-28T10:51:03.273
16

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?

Edit
Report

1 Answer

1

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 ;-)

answered 2009-10-28T18:47:57.897

Your Answer