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
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>() {}.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>() {}.getType();
while ((line = buffReader.readLine()) != null) {
services.addAll(gson.fromJson(line, type));
}
buffReader.close();
} catch (IOException e) {
return -1;
}
return 0;
}