简体   繁体   中英

What's a safe way to store data in Android?

I've been using singletons to store data that is loaded when my application started. This data is used throughout the lifetime of my app, but doesn't need to be persisted for future launches. I've started hitting the issue though that my singletons are garbage collected and their data is wiped. Does the singleton pattern just not make any sense on Android? Using local storage or a local database seems like overkill, but I'm not sure what else to do to guarantee my data is safe for the lifetime of my app.

Thanks!

I've started hitting the issue though that my singletons are garbage collected and their data is wiped.

No, they are not. By definition, a singleton (static data member) cannot be garbage collected.

Most likely, what you are seeing is that your process is being terminated .

Does the singleton pattern just not make any sense on Android?

As a caching mechanism, it is fine.

I'm not sure what else to do to guarantee my data is safe for the lifetime of my app

A static data member is "safe for the lifetime" of your process . If you want data to survive process termination, you will need to store that data in a database, SharedPreferences , or some other sort of file.

Are you holding onto a reference to the singletons in the Application ( http://developer.android.com/reference/android/app/Application.html ) level of the app? That should keep them persistent for the most part (unless they're byte[] or something else huge).

The safest bet, however, is to assume that data will be garbage collected and structure your code with that assumption. If it's something from the web, define an asynchronous callback to load the data and then populate your views. If it's something local that is not user-generated, use the async to grab it from disk. If it's user generated, you might need to set up a database (which you can empty when you restart the app) to keep track of data.

But, if you haven't, tried keeping references to your singletons in the Application first. Brief intro here: http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM