What Is The Most Suitable Way To Store Object In Android?
Hello in my app I need to store single object with several fields. At this moment it is saved like this @Override public Object onRetainNonConfigurationInstance() { re
Solution 1:
Taken from my calculator:
@SuppressWarnings("unchecked")
privatevoidloadState() {
ObjectInputStream ois;
try {
ois = newObjectInputStream(openFileInput(FILE_STATE));
state = ((State) ois.readObject());
ois.close();
ois = newObjectInputStream(openFileInput(FILE_HISTORY));
historyListAdapter.setItems((List<String>) ois.readObject());
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
state = newState();
} catch (IOException e) {
e.printStackTrace();
state = newState();
} catch (ClassNotFoundException e) {
Toast t = Toast.makeText(this, "Error parsing saved state",
Toast.LENGTH_SHORT);
t.show();
state = newState();
}
setState(state);
}
privatevoidsaveState() {
ObjectOutputStream oos;
try {
oos = newObjectOutputStream(openFileOutput(FILE_STATE,
Context.MODE_PRIVATE));
oos.writeObject(state);
oos.close();
oos = newObjectOutputStream(openFileOutput(FILE_HISTORY,
Context.MODE_PRIVATE));
oos.writeObject(historyListAdapter.getItems());
oos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@OverrideprotectedvoidonPause() {
saveState();
super.onPause();
}
Call loadState() in onCreate().
Worked fine for me, I know its not advised to use java serialization in android, but I didn't encounter any errors or bugs whatsoever. No issues with performance either.
You should of course tweak error handling depending on your application.
Solution 2:
Depends how big your object is. Try with shared preferences: http://developer.android.com/guide/topics/data/data-storage.html#pref
Combination of preferences, right places to populate/read from it, and some static init method could do things for you.
Hope it helps.
Post a Comment for "What Is The Most Suitable Way To Store Object In Android?"