1

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?

Jibran Khan
  • 3,236
  • 4
  • 37
  • 50
Sergei Ledvanov
  • 2,131
  • 6
  • 29
  • 52
  • 1
    Many of your options are covered in the Developer's Guide: [Data Storage](https://developer.android.com/guide/topics/data/data-storage.html) – Sam Jun 29 '13 at 12:23
  • Just use the database http://developer.android.com/guide/topics/data/data-storage.html#db – Patrick Jun 29 '13 at 12:24
  • for3st, I am dealing with the binary data, so SQLite is a bad option. Sam, I've seen this link, but what option from that list do you vote for? – Sergei Ledvanov Jun 29 '13 at 15:03

3 Answers3

1

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

Community
  • 1
  • 1
stinepike
  • 54,068
  • 14
  • 92
  • 112
0

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

Community
  • 1
  • 1
Lohit
  • 126
  • 8
  • Regarding `OnSaveInstance` How can this help if I quit activity with `finish()` and when I re-create it again, `onCreate(savedInstanceState)` is called with `null`? – Sergei Ledvanov Jun 29 '13 at 15:04
0

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

Paul Burke
  • 25,496
  • 9
  • 66
  • 62
  • How can this help if I quit activity with `finish()` and when I re-create it again, `onCreate(savedInstanceState)` is called with `null`? – Sergei Ledvanov Jun 29 '13 at 15:04
  • `onSaveInstanceState` will only work for config changes. You can definitely persist the changes to a file using `openFileOutput`, but using a database _may_ result in quicker I/O. Just make sure the file operations are not performed on the UI thread. – Paul Burke Jun 30 '13 at 12:41