【发布时间】:2015-01-15 17:17:15
【问题描述】:
我有一个包含很多对象的类
private class MyDataStuff{
private String mostInterestingString;
private int veryImportantNumber
//...you get the idea
public MyDatastuff{
//init stuff...
}
//some getter methods
}
此外,我有一个类,我们称它为 User,它有一个 MyDataStuff 列表,一些 longs,Strings 等。
我想将User 的对象存储到内部存储上的文件中。我用下面的代码试了一下:
//loading
try{
FileInputStream fis = this.getApplicationContext().openFileInput("UserData.data");
ObjectInputStream is = new ObjectInputStream(fis);
User loadedUser = (User) is.readObject();
is.close();
fis.close();
appUser = loadedUser;
}catch (Exception e){
Log.e("MainActivity", "Error: loading from the internal storage failed - \n" + e.toString());
}
//Saving
if(appUser == null){
Log.e("MainActivity", "Create new User");
appUser = new User();
try{
FileOutputStream fos = this.getApplicationContext().openFileOutput("UserData.data", Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
}catch (Exception e){
Log.e("MainActivity", "Error: Failed to save User into internal storage - \n" + e.toString());
}
}
这导致java.io.NotSerializableException。我阅读了可序列化的文档并制作了
测试类 User 实现 Serializable 并删除除 long 和 Strings 之外的每个属性。
它仍然会导致这个异常,这让我相信 Strings 或 longs 在默认情况下也不能序列化。
我需要将对象保存为当前状态。有没有更好的方法来做我想做的事情, 如果没有,我该如何解决这个问题?
【问题讨论】:
-
您应该专注于保存数据的标准方法。将对象保存到 XML 文件或数据库中。 api 21 有一个可持久的包,你可以将一个打包的对象放入其中,但我还没有尝试过。
标签: java android serialization save