Using the Android Application class to persist data

Dave, what kind of data is it? If it's general data that pertains to the application as a whole (example: user data), then extend the Application class and store it there. If the data pertains to the Activity, you should use the onSaveInstanceState and onRestoreInstanceState handlers to persist the data on screen rotation.


If you want to access the "Global Singleton" outside of an activity and you don't want to pass the Context through all the involved objects to obtain the singleton, you can just define a static attribute in your application class, which holds the reference to itself. Just initialize the attribute in the onCreate() method.

For example:

public class ApplicationController extends Application {
    private static ApplicationController _appCtrl;

    public static ApplicationController getAppCtrl()
    {
         return _appCtrl;
    }
}

Because subclasses of Application also can obtain the Resources, you could access them simply when you define a static method, which returns them, like:

public static Resources getAppResources()
{
    return _appCtrl.getResources();
}

But be very careful when passing around Context references to avoid memory leaks.


Those who count on Application instance are wrong. At first, it may seem as though the Application exists for as long as the whole app process exists but this is an incorrect assumption.

The OS may kill processes as necessary. All processes are divided into 5 levels of "killability" specified in the doc.

So, for instance, if your app goes in the background due to the user answering to an incoming call, then depending on the state of the RAM, the OS may (or may not) kill your process (destroying the Application instance in the process).

I think a better approach would be to persist your data to internal storage file and then read it when your activity resumes.

UPDATE:

I got many negative feedbacks, so it is time to add a clarification. :) Well, initially I realy used a wrong assumption that the state is really important for the app. However if your app is OK that sometimes the state is lost (it could be some images that will be just reread/redownloaded), then it is fully OK to keep it as a member of Application.


I don't think 500kb will be that big of a deal.

What you described is exactly how I tackled my problem of losing data in an activity. I created a global singleton in the Application class and was able to access it from the activities I used.

You can pass data around in a Global Singleton if it is going to be used a lot.

public class YourApplication extends Application 
{     
     public SomeDataClass data = new SomeDataClass();
}

Then call it in any activity by:

YourApplication appState = ((YourApplication)this.getApplication());
appState.data.UseAGetterOrSetterHere(); // Do whatever you need to with the data here.

I discuss it here in my blog post, under the section "Global Singleton."