what is the easyest or native way to save a list of objects in a android application?
i need to save it and then load it when the app starts again.
would be nice
I usually don't provide full answers, but since it's in my clipboard...
This should work with any List implementation.
Further you'll need to to define / exchange Constants.EXTERNAL_CACHE_DIR
and might want to use something else than the UI-Thread for production.
public static void persistList(final List<String> listToPersist, final String fileName) {
FileWriter writer = null;
BufferedWriter bufferedWriter = null;
File outFile = new File(Constants.EXTERNAL_CACHE_DIR, fileName);
try {
if (outFile.createNewFile()) {
writer = new FileWriter(outFile);
bufferedWriter = new BufferedWriter(writer);
for (String item : listToPersist) {
bufferedWriter.write(item + "\n");
}
bufferedWriter.close();
writer.close();
}
} catch (IOException ioe) {
Log.w(TAG, "Exception while writing to file", ioe);
}
}
public static List<String> readList(final String fileName) {
List<String> readList = new ArrayList<String>();
try {
FileReader reader = new FileReader(new File(Constants.EXTERNAL_CACHE_DIR, fileName));
BufferedReader bufferedReader = new BufferedReader(reader);
String current = null;
while ((current = bufferedReader.readLine()) != null) {
readList.add(current);
}
} catch (FileNotFoundException e) {
Log.w(TAG, "Didn't find file", e);
} catch (IOException e) {
Log.w(TAG, "Error while reading file", e);
}
return readList;
}
Have u tried shared preferneces..? when ur app is about to exit, save that using shared preferences and again when app starts, load that preference.
Let your items stored in the LinkedList
implement Parcelable so you can put them in your bundle
. The in onSaveInstance
you can put your objects in the bundle
using:
bundle.putParcelableArrayList ("key", list);
and in onRestoreInstanceState
of your Activity
get the data back from that bundle
using :
bundle.getParcelableArrayList();