Using the Android Application class to persist data

来源:互联网 发布:淘宝搜索什么能看片 编辑:程序博客网 时间:2024/04/27 07:42

http://stackoverflow.com/questions/4208886/using-the-android-application-class-to-persist-data
Question:

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!


Answer:

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


原创粉丝点击