Title: Keep application state on android
Tags: android
Question: I am having trouble saving the state/singleton of my application.

When the application starts a loading screen (activity) is shown and a singleton is initialized with values from a webservice call (note that network access cannot run on the main thread).

After the singleton is created I open my main activity. Note that values from the singleton are required to build the layout.

Now assume the app goes in the background and is killed there (e.g. because of low memory). My singleton instance is deleted as the app is killed. When I switch back to my app it tries to recreate the main activity. As I mentioned earlier the values from the singleton are required to build the layout, so this leads to a NullPointerException (when I try to access members of the singleton, as it is not there anymore).

Can I somehow tell android to start the first loading activity after the app was killed? It would be great if I could refresh the singleton before the layout is recreated, but this seems to be a problem as network calls can not be on the main thread and therefore not block until the refresh is finished.
I assume that I could save the singleton in all activities onStop and recreate it in the onCreate methods, but this seems a bit too unpredictable and would probably lead to a inconsistent state...

Another way could be to just always finish my activity onStop, but this would lead to losing on which tab the user last and so on, even if the app is not killed, so this is not a good option.

Any ideas on how to solve this? 

Comment: Show code or at least code snippets. Also show the logcat for the 'crash' - we can't really if all you say is "...leads to a crash...".

Comment: The problem is not the crash, the problem is that the singleton object is null as the app was killed in the background and when I switch back to it it tries to load the last activity, which has to access the singleton to create its layout.

Here is the accepted answer: Why not just use a SharedPreferences instead of a singleton?

Anytime you want to save some global state, commit it to preferences. Anytime you want to read the global state, read it back from preferences. 

Then you don't have to concern yourself with application lifecycle at all, as your data will always be preserved regardless of what the phone is doing.

Comment for this answer: SharedPreferences is not universal utility. In my case I have 100k strctured data and images. To save/load via SharedPreferences is not goos idea - I tried, but loading takes 10 seconds.
Comment for this answer: This will definitely do, I will evaluate this tomorrow and give feedback if it works for me :) I really like the idea of not having to deal with the application lifecycle

Here is another answer: For something like that I used a pseudo singelton object as a Application class. This object will be created on the beginning and will be in the memory. But note that the system will terminate the application if the memory is needed by other applications. However this object is persitent even if all activities are temporally terminated.

To use that you need to declare that in your android manifest like here:

```<application android:label="@string/app_name"
             android:icon="@drawable/icon"
             android:description="@string/desc"
             android:name=".MySingeltonClass"
             ...
```

Here is a code example:

```public abstract class MySingeltonClass extends Application {
    // ...

    public void informClientOnline() {
        clientOnline=true;
        Log.v(LOG_TAG, "Client is online!");
    }

    public void informClientShutdown() {
        clientOnline=false;
        Log.v(LOG_TAG, "Client is going offline. Waiting for restart...");
        Timer t=new Timer("shutdowntimer", false);
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                if(!clientOnline) {
                    Log.v(LOG_TAG, "Client has not restartet! Shutting down framework.");
                    shutdown();
                    System.exit(0);
                }
            }
        }, 5000);
    }
}
```

this two functions are called like this:

```((MySingeltonClass)getApplicationContext()).informClientOnline();
```

Comment for this answer: My solution was to call on oncreate a *here am i* method and a *good by* method in ondestroy... I'll add an example.
Comment for this answer: The application object will exists even if temporally all activities are closed. That is why I check that manually and save than all custom states in my `shutdown()` method.
Comment for this answer: I call the methods `informClientOnline()` and `informClientOnline()` in every activity in `oncreate`/`ondestroy`. So it's simple to know that. If the last activity is destroyed you know that you have to save your state before your app will be terminated. How every I think it is a much better design to use contentproviders and sync services. But that is really a heavy topic.
Comment for this answer: The "system will terminate" part is exactly my problem, as I need a way to recreate the object after that.
Comment for this answer: Thank you, however I do not see how this helps restore my singleton (ok, I guess you mean my singleton should just be this application object. Now mind the part that the data has to be filled with a webservice call. The application will be closed, reopened, the Application object will be created, I can schedule my webservice call, but then my activity is opened and the call is not finished, I get a bad layout).
Comment for this answer: How do you check manually and save anything if you are not informed that the app is killed? Maybe I do not get something or something is still missing...
Comment for this answer: This will not work, as onDestroy will not even be called. Look at the Activity Lifecycle: The app goes to the background, onStop() is called. Now the app is killed, so the onDestroy will not even be called then, so you cannot know for sure when the app or an activity is terminated.

Here is another answer: You could save your Singleton when ```onSaveInstanceState()``` in the Activity gets called. All you need to do is to make it implement ```Parcelable``` (it's Androids own form of serialization), then you can put it in the ```outState``` ```Bundle``` in ```onSaveInstanceState()``` which will allow you to retrieve it laver in ```onCreate()``` or ```onRestoreInstanceState()``` in the Activity, whichever you like.

I've included an example for you:

```public class TestActivity extends Activity {

    private MySingleton singleton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState.containsKey("singleton")) {
            singleton = savedInstanceState.getParcelable("singleton");
        } else {
            singleton = MySingleton.getInstance(5);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("singleton", singleton);
    }

    public static class MySingleton implements Parcelable {

        private static MySingleton instance;
        private int myData;

        private MySingleton(int data) {
            myData = data;
        }

        public static MySingleton getInstance(int initdata) {
            if(instance == null) {
                instance = new MySingleton(initdata);
            }

            return instance;
        }

        public static final Parcelable.Creator<MySingleton&gt; CREATOR = new Creator<TestActivity.MySingleton&gt;() {

            @Override
            public MySingleton[] newArray(int size) {
                return new MySingleton[size];
            }

            @Override
            public MySingleton createFromParcel(Parcel source) {
                return new MySingleton(source.readInt());
            }
        };

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel parcel, int flags) {
            parcel.writeInt(myData);
        }

    }

}
```

Comment for this answer: Then what will happen with more than one activity? I guess the singleton would be saved/serialized independently (with possibly different values) and with every onCreate I change my singleton to something different again (which leads to a inconsistent state)
Comment for this answer: Yes, but if I serialize my singleton I kind of "freeze" it, right? Now assume one activity opens an activity that is only open for a short time (like a dialog). After this dialog-kind activity is closed it saves its state, right? Now ten minutes later the main activity saves its state (so the state 10 minute later). After the app is killed and comes back to life the main activity will restore the singleton. But when the dialog comes back it will resore the 10min earlier state, isn't that right?
Comment for this answer: Your singleton cannot be in a different state in each activity if it's a true singleton. It's the same object everywhere, that's why it's a singleton :)
Comment for this answer: Okay sure I see your problem. You could do some sort of serialization (Parcelable doesn't support writing the object to disk) that always saves the object to the same file. Then when your activity is re-created you check if an instance of your singleton exists (something like a `isInstanceAvailable` boolean method in your singleton), if it is, then you grab it, if it isn't then you re-create it from the object stored on disk. But this may be a somewhat inelegant solution to your problem (serialization is reportedly slow on Android), and I must admit I'm not an expert on this subject :)

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2012:00:10/26/12', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<android>', 'Title': 'Keep application state on android', 'ViewCount': 1846, 'id': 13094346, 'user_AboutMe': '<p>Passionate developer and author of GitRewrite, a tool to rewrite certain parts of git history:\n<a href="https://github.com/TimHeinrich/GitRewrite" rel="nofollow noreferrer">https://github.com/TimHeinrich/GitRewrite</a></p>\n', 'user_AccountId': 438151.0, 'user_DisplayName': 'Tim', 'user_Reputation': 2001.0, 'user_Views': 237.0, 'user_id': 826244.0}}