I have an ArrayList which contains custom Service objects. I want to write the whole ArrayList to a File and be able to read it afterwards.
I tried Gson for that, but it
I would recommend using serialization for such an operation. You can implement Java's Serializable interface and you are then able to deflate your objects into a .ser file and then inflate them back from that very file to call the methods you need from them.
Here is a nice tutorial regarding Serialization - http://www.tutorialspoint.com/java/java_serialization.htm
With little tweaks your json approach works fine. However the solution by Booch would be the ideal recommendation for these kind of requirements.
Since you are appending to a file the below methods will append the objects to file and on reading it will read all previously written list and make it to a single list. Since services is a global variable you should consider initializing it or clearing it before read method to avoid duplicates.
public int saveListToFile() {
String filename = "service_entries";
File file = new File(getFilesDir(), filename);
try {
BufferedWriter buffWriter = new BufferedWriter(new FileWriter(file, true));
Gson gson = new Gson();
Type type = new TypeToken<List<Service>>() {}.getType();
String json = gson.toJson(services, type);
buffWriter.append(json);
buffWriter.newLine();
buffWriter.close();
} catch (IOException e) {
return -1;
}
return 0;
}
public int readCurrentList() {
String filename = "service_entries";
File file = new File(getFilesDir(), filename);
try {
BufferedReader buffReader = new BufferedReader(new FileReader(file));
String line;
Gson gson = new Gson();
Type type = new TypeToken<List<Service>>() {}.getType();
while ((line = buffReader.readLine()) != null) {
services.addAll(gson.fromJson(line, type));
}
buffReader.close();
} catch (IOException e) {
return -1;
}
return 0;
}