Java 在android中保存持久内部数据对象列表
我有一个类,有很多对象,比如Java 在android中保存持久内部数据对象列表,java,android,serialization,save,Java,Android,Serialization,Save,我有一个类,有很多对象,比如 private class MyDataStuff{ private String mostInterestingString; private int veryImportantNumber //...you get the idea public MyDatastuff{ //init stuff... } //some getter methods } 此外,我还有一个类,
private class MyDataStuff{
private String mostInterestingString;
private int veryImportantNumber
//...you get the idea
public MyDatastuff{
//init stuff...
}
//some getter methods
}
此外,我还有一个类,我们称它为User
,它有一个MyDataStuff
列表、一些long、字符串等。
我想将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
。我阅读了可序列化的文档并制作了
testwise类用户实现Serializable并删除除long和string之外的所有atribute。
它仍然会导致这个异常,这让我相信字符串或长字符在默认情况下也不可序列化
我需要将对象保存为当前状态。有没有更好的方法来做我想做的事,
如果没有,如何解决此问题?请仔细查看您的序列化代码
//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);
...
您正在创建一个新的用户
对象,但您正在序列化这个
,我猜它可能是一个活动
或片段
。因此,您将收到一个notserializableeexception
String
s和Long
s可以序列化而不会出现任何问题。但是,如果最终的用户
实现将有一个MyDataStuff
列表,则还必须将其类标记为可序列化。如果要存储用户对象,则需要编写appUser对象,而不是“this” 您应该专注于保存数据的标准方法。将对象保存到XML文件或数据库中。api 21有一个可持久化的捆绑包,您可以将一个包裹的对象放入其中,但我还没有尝试过。多么愚蠢的错误,似乎我需要更多的咖啡。非常感谢,先生。