Rich
Rich

Reputation: 4207

Preserving Android Activity data

My Android application has an array of fairly-complex objects that I use to store user data and I would like to save this array and restore the data from previous sessions when running the application. The objects in question have several pieces of data (hence making the objects in the 1st place), so I really don't want to write out all the components to SharedPreferences (which is one idea I had for doing this). I also looked into onSaveInstanceState(), that doesn't appear to be called reliably enough to help me.

The object in question is Serializable, but it doesn't appear that there's a putSerializable() method I can use, so I can't see how this helps me with this issue.

Can anyone provide a suggest for dumping this data somewhere non-volatile and re-using later??

Upvotes: 0

Views: 43

Answers (3)

Marco
Marco

Reputation: 707

You could use yours application's internal storage to save those data and restore them every time you need through a FileInputStream.

If your object is complex, in order to save space, you could serialize it with Gson and then save it as a simple string, always in the internal storage.

Example:

Object yourObject = new Object;
Gson gson = new Gson();
String serializedObject = gson.toJson(yourObject);

//write to internal storage
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

You could read that string in this way:

String filename = "your_file";
FileInputStream fis = openFileInput(filename);
StringBuffer sBuffer = new StringBuffer();
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
while((strLine = dataIO.readLine()) != null)
{
sBuffer.append(strLine+”\n”);
}
dataIO.close();
fis.close();

and finally deserialize it.

Upvotes: 0

Yoni Samlan
Yoni Samlan

Reputation: 38065

If you're set on just rolling with Serializable, you could consider the same sort of approaches used in plain Java-land for writing a serializable to a String to store in a SharedPreference; see this question for one approach.

Otherwise, I think you're better off using something like GSON, like Zanna suggeted.

Upvotes: 1

Kent Hawkings
Kent Hawkings

Reputation: 2793

Using SharedPreferences is not ideal for anything beyond fairly simple key-value pairs. Your best bet would be to use a SQLite Database. Check the developer docs for more info.

Upvotes: 1

Related Questions