I need a way to save an ArrayList of objects. I have browsed similar issues in the site and I (seem 😉 to have implemented what I found, but I get two problems:
- If I define the class as
Serializableand put the constructor, it crashes at launch - Otherwise, It does not save the array
Can you please help? I am developing code for a volunteer’s project and I am stuck…
Thank you a lot in advance.
My application has the following defined class: Globals (file Globals.java)
public class Globals extends Application implements Serializable {
private int position=-1;
private ArrayList<RaccoltaPunti> raccoltePuntiList = new ArrayList<RaccoltaPunti>();
public static final long serialVersionUID = 1L;
/** constructor - seem required by Serializable, but creating it crashes app */
public Globals(int position, ArrayList<RaccoltaPunti> raccoltePuntiList) {
this.position = position;
this.raccoltePuntiList = raccoltePuntiList;
}
// {getters and setters…}
public void saveData(){
String filename = getResources().getString(R.string.GLB_filename);
String fileWithPath = this.getFilesDir().getPath().toString()+"/"+filename;
Toast.makeText(this, "Salvataggio testo..."+ fileWithPath, Toast.LENGTH_LONG).show();
try {
FileOutputStream fos = new FileOutputStream(fileWithPath);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this.raccoltePuntiList);
oos.close();
Toast.makeText(Globals.this, "DatiSalvati ", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.e("FileSave", "CDM - IOException", e);
Toast.makeText(this, "Errore saving file", Toast.LENGTH_LONG).show();
}
}
}
The class referenced is: RaccoltaPunti.java
public class RaccoltaPunti {
private String nomeRaccolta;
private String nomePromoter;
private String numeroTessera;
private Long puntiPusseduti;
private String dataScadenzaPunti;
private String sitoWeb;
private String sitoWebUsername;
// constructor, getters and setters…….
}
The problem seems resolved (now the file is successfully saved without errors and by manually opening it it seems to contain all the info).
Thank you to you all.
I summarise the solution for the benefit of any other future reader with the same issue.
The problem was resolved by making the class
RaccoltaPuntiSerializable, as per following code fragment:I noted that
RaccoltaPuntihad already a constructor with parameters:For reference, the error reported in the log was referring to the line of code:
Regarding the constructor for the
Globalsclass, my experiments showed that everything is working by just commenting it out. I did not try all possible combinations (i.e. with or without parameters): I just removed it.Thank you all who helped.