113

I'm working on a fairly complex Android application that requires a somewhat large amount of data about the application (I'd say a total of about 500KB -- is this large for a mobile device?). From what I can tell, any orientation change in the application (in the activity, to be more precise) causes a complete destruction and recreation of the activity. Based on my findings, the Application class does not have the same life-cycle (i.e. it is, for all intents and purposes, always instantiated). Does it make sense to store the state information inside of the application class and then reference it from the Activity, or is that generally not the "acceptable" method due to memory constraints on mobile devices? I really appreciate any advice on this topic. Thanks!

2
  • 9
    Just keep in mind that data in your Application can still be deleted if your app goes into the background, so this is not a solution to persisting data you always want to be able to get back. It just serves as a method of not having to recreate expensive objects as often. Nov 17, 2010 at 20:57
  • 2
    Mayra; I don't think the app is "usually" deleted (though, as someone points out later in this thread, it "can" be). I'm probably going to go with some type of a "hybrid" approach of using the application to store and load the data, but then use the "android:orientation" attribute on the activity in the manifest file to override the normal behavior of tearing down and rebuilding the activity. All this, of course, assumes that the application can determine "when" it's being destroyed so that the data can be persisted.
    – Dave
    Nov 18, 2010 at 12:30

7 Answers 7

133

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."

8
  • 1
    Unfortunately the blog post in question is no longer available at that address. Mar 4, 2014 at 1:22
  • 1
    I've been moving things around on my site. Until it's fixed, you can find it on archive.org here: web.archive.org/web/20130818035631/http://www.bryandenny.com/… Mar 4, 2014 at 14:30
  • 1
    i know this is an old post but i just came across a problem that this might solve, however this class needs to be declaired in the manifest somehow, no? i cannot acsses the class so feel like this is what i am missing...
    – Ziv Kesten
    Jun 17, 2014 at 19:37
  • 1
    @ZivKesten How about adding the name= attribute to the application tag inside manifest?
    – MikeC
    Jul 28, 2014 at 6:20
  • @mgc thank you its been a while, and yes that is how i eventually worked it out, also i created instances of that class wherever i needed by giving it the getApplicationContext() with a cast to this class
    – Ziv Kesten
    Jul 28, 2014 at 6:57
58

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.

6
  • 15
    If the Application is killed, then who cares, right? The application is gone. As I understand it, Android will reclaim processes which contain memory like Activities. If the process containing the Application is killed (if Android will even do that?), that is essentially like killing the app. The user will need to launch the app again and, at that point, who cares? It's a new instance of the application.
    – Andrew
    Nov 17, 2010 at 22:06
  • 16
    This was an unplesant surprise for us in production. Believe me Android kills processes, it just depends on RAM state and other factors described in the documentation. It was a nightmare for us so I just share my real experience. Well we did not have this on emulators, but in real world some devices are 'overloaded' with apps, so killing a background process is a normal situation. Yes, if user then decides to get the app up into foreground - the OS restores its stack including the Application instance, however there will not be your static data you count on unless you persisted it. Nov 17, 2010 at 22:24
  • 2
    I think I'm going to probably use a hybrid approach. I already knew about the manifest trick to override the orientation change (which has other benefits). Since the application is a game, I'm not sure persisting the data between launches is "important" enough; though it probably wouldn't be terribly hard as most of the data can be serialized (though I wouldn't want to serialize and unserialize between every orientation change). I definitely appreciate the input. I wouldn't say those that depend on the App instance are "wrong." A lot depends on the app :).
    – Dave
    Nov 18, 2010 at 12:28
  • 1
    @Arhimed you are generalizing your answer too much. And suggesting a narrow approach based on your assumption. False Assumption: The data held in the static variables needs to be persisted across sessions of the app. There may be numerous use cases where the data is trivial and need not be persisted immediately. Jan 5, 2012 at 16:19
  • 2
    I have about 1mb data with complicated structure. Serialize/deserialize can cost me up to 2-3 seconds when device is overloaded with work. Idea to save/load between activities cost too much time. I use application as storage. Of course my data class stored in application instance have check on every metod - is data still alive or have to be loaded. So Dave have to: 1. provide load /save finctions 2.keep data in application. 3. Triple check logic for accesing data.
    – Kostadin
    Aug 13, 2012 at 7:49
6

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.

2
  • 6
    You forgot to note that you must add android:name=". ApplicationController" xml attribute the application tag in your manifest for the class to be instantiated.
    – eggie5
    Jun 29, 2012 at 22:02
  • You don't actually need to extend Application to do this. You can declare a static member variable in any class to do this. Aug 9, 2017 at 13:48
2

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.

1
  • What if the data is really big to store in a Parcel? This is what im getting : android.os.TransactionTooLargeException: data parcel size 838396 bytes Jan 25, 2019 at 9:38
1

You can actually override the orientation functionality to make sure that your activity isn't destroyed and recreated. Look here.

2
  • 18
    You can do a lot of things. It doesn't mean they're good ideas. This is not a good idea.
    – Andrew
    Nov 17, 2010 at 22:07
  • Testing by changing the screen orientation is the easiest way to make sure your app does what Android assumes it to do. Jan 31, 2013 at 5:19
0

You can create Application class and save your all data on that calss for use that anywhere in your application.

0

I know this is the very old question but using the ViewModel from the jetpack components is the best way to preserve the data between Activity rotation.

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

Not the answer you're looking for? Browse other questions tagged or ask your own question.