Ryan Sayles
Ryan Sayles

Reputation: 3431

Android save a list of custom objects

I'm creating an app that has a sort of Master-Detail ListView of custom objects. My Adapter is an array of custom objects:

ArrayAdapter<Record> adapter;

which is being added to a ListView dynamically. I need to preserve the list, so that when the user opens the app again the list is how it was when they closed it. I looked into using SharedPreferences since that is what I'm using for the settings of my app but I can't figure out how to save a list of my custom objects with it. After reading documentation it seems like SharedPreferences is just for simple key-value pairs. Does anyone know how I can save this list? Any help would be greatly appreciated!

Upvotes: 0

Views: 57

Answers (1)

Itzik Samara
Itzik Samara

Reputation: 2288

Example: Writing:

List<Record> records;
ObjectOutputStream stream = new ObjectOutputStream(context.openFileOutput("records.dat",Context.MODE_PRIVATE);
stream.writeObject(list);
stream.close();

Example: Reading:

       ObjectInputStream inputStream = new ObjectInputStream(context.openFileInput("records.dat"));
  records = (List<Records)inputStream.readObject();
  inputStream.close(); 

just make sure the classes your are using are Parcelable

Hope it helps you.

Upvotes: 1

Related Questions