Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Android Application class to persist data

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!

like image 439
Dave Avatar asked Nov 17 '10 20:11

Dave


People also ask

How can I persist information in an Android device?

Android supports the following ways of storing data in the local file system: Files - You can create and update files. Preferences - Android allows you to save and retrieve persistent key-value pairs of primitive data type. SQLite database - instances of SQLite databases are also stored on the local file system.

What is the use of application class in Android?

Overview. The Application class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created.

What is Android application life cycle?

An Android activity goes through six major lifecycle stages or callbacks. These are: onCreate() , onStart() , onResume() , onPause() , onStop() , and onDestroy() . The system invokes each of these callbacks as an activity enters a new state.

How do you declare an application class in manifest?

Open AndroidManifest. xml file of your app and locate <application> tag. Add an attribute android:name and set it to your new application class.


1 Answers

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

like image 86
Bryan Denny Avatar answered Oct 11 '22 11:10

Bryan Denny