我需要一种方法来保存ArrayList
个对象。我在网站上浏览了类似的问题,我(似乎;-)已经实现了我发现的内容,但我遇到了两个问题:
Serializable
并放置构造函数,它会在启动时崩溃
你能帮帮忙吗?我正在为一个志愿者项目开发代码而且我被卡住了......
提前多多谢谢你。
我的应用程序具有以下定义的类:Globals
(文件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();
}
}
}
引用的类是: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…….
}
答案 0 :(得分:2)
RaccoltaPunti
必须为Serializable
。答案 1 :(得分:0)
尝试创建默认构造函数:
public Globals(){
}
由于类扩展了Application类,因此它将通过反射从外部调用,它可能需要一个默认的构造函数。默认情况下,如果您没有编写任何构造函数,则默认构造函数已经存在。
使RaccoltaPunti也可序列化
答案 2 :(得分:0)
问题似乎已解决(现在文件已成功保存而没有错误,并且通过手动打开它似乎包含所有信息)。
谢谢大家。
为了同样的问题,我总结了解决方案,以便其他未来的读者受益。
根据以下代码片段制作课程RaccoltaPunti
Serializable
,问题已解决:
import java.io.Serializable;
...
public class RaccoltaPunti implements Serializable {
...
我注意到RaccoltaPunti
已经有一个带参数的构造函数:
public RaccoltaPunti(
String nomeRaccolta,
String nomePromoter,
String numeroTessera,
Long puntiPusseduti,
String dataScadenzaPunti,
String sitoWeb,
String sitoWebUsername) {
作为参考,日志中报告的错误是指代码行:
oos.writeObject(this.raccoltePuntiList);
关于Globals
类的构造函数,我的实验表明,只需将其注释掉即可。我没有尝试所有可能的组合(即有或没有参数):我刚把它删除了。
谢谢所有帮助过的人。