Sergei Ledvanov
Sergei Ledvanov

Reputation: 2251

How to save data in activity of later use

I have an Activity A that opens Activity B. During B's lifecycle, it creates lots of data that is important for later use. When I leave Activity B, it gets destroyed. I want that when a user opens B next time, that important data would be restored.

So the question is, how to store that important data?

I had several assumptions:

  1. SharedPreferences (context.getPrecerence(MODE_PRIVATE)). This is not a good options, because it allows saving only primitive types. I need to save java.io.Serializable object (or at least Parcelable).

  2. Static variable - not an option. I want my data to remain even if JVM destroys my process when the user navigates to some other app.

  3. Context.openFileOutput(). Is this OK to make I/O every time I enter activity/quit it?

Something else?

Upvotes: 1

Views: 328

Answers (3)

stinepike
stinepike

Reputation: 54692

You can save to SharedPreference using gson.jar. see this answer related to this

Upvotes: 1

Paul Burke
Paul Burke

Reputation: 25584

If you simply want to retain the data through config changes, onSaveInstanceState(Bundle) is what you're looking for. Otherwise, use a database.

http://developer.android.com/training/basics/activity-lifecycle/recreating.html#SaveState

Upvotes: 0

Lohit
Lohit

Reputation: 126

You can use a database if the data is user specific. The database can be accessed whenever user comes back.

Or you can use Bundle (use OnSaveInstance(Bundle)).

This answer is useful in Bundles

Upvotes: 0

Related Questions