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 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 readList(final String fileName) {
List readList = new ArrayList();
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;
}