I have a class with a lot of objects like
private class MyDataStuff{
private String mostInterestingString;
private int veryImportantNumber
//...you get the idea
public MyDatastuff{
//init stuff...
}
//some getter methods
}
Furthermore I have a class, lets call it User that has a list of MyDataStuff , some longs, Strings etc.
I want to store an object of User into a file on the internal storage. I tried it with following code:
//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());
}
}
This leads to an java.io.NotSerializableException. i read the Serializable-documentation and made
testwise the class User implement Serializable and deleted every atribute except for longs and Strings.
It still leads to this Exception wich makes me believe that Strings or longs aren't serializable by default either.
I need to save the object in its current state. Is there a better way in doing what I am trying to do, and if not, how can I fix this problem?