Using the Android Application class to persist data
Asked Answered
M

7

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!

Mcfarlane answered 17/11, 2010 at 20:34 Comment(2)
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.Zwick
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.Mcfarlane
H
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."

Hesper answered 17/11, 2010 at 20:41 Comment(8)
Unfortunately the blog post in question is no longer available at that address.Almatadema
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/…Hesper
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...Awe
@ZivKesten How about adding the name= attribute to the application tag inside manifest?Hagiology
@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 classAwe
Is Application never destroyed? Because normal singleton classes do get destroyed!Hercegovina
Bryan i will dis-agree with due respect. Because application class will lose the data if your application processed is being killed by the OS.(in low memory situation).Siegfried
The Application object may be destroyed, and unless the getter-method recreates the singleton you will have a null reference error if you're unlucky. developerphil.com/dont-store-data-in-the-application-objectWorser
R
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.

Renewal answered 17/11, 2010 at 21:35 Comment(6)
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.Monochrome
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.Renewal
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 :).Mcfarlane
@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.Trothplight
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.Lest
This is the correct answer to a different question. If you are only persisting data for the Application session then it's 100% correct to persist in either a Singleton or with an object within the Application class. You should ALWAYS prefer persisting in memory as opposed to disk if it's only for session information. Persisting to disk is not only slower but it's going to wear out the user's hardware faster.Narrow
R
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.

Richelle answered 17/11, 2010 at 21:36 Comment(2)
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.Ambient
You don't actually need to extend Application to do this. You can declare a static member variable in any class to do this.Diadromous
M
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.

Monochrome answered 17/11, 2010 at 22:3 Comment(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 bytesMatelda
G
1

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

Garnierite answered 17/11, 2010 at 20:51 Comment(2)
You can do a lot of things. It doesn't mean they're good ideas. This is not a good idea.Monochrome
Testing by changing the screen orientation is the easiest way to make sure your app does what Android assumes it to do.Motorman
K
0

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

Kailyard answered 3/7, 2015 at 12:17 Comment(0)
S
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.

Snodgrass answered 1/11, 2019 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.