什么是对象存储在Android上最合适的方式? [英] 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() {
return UILApplication.advert;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Advert retainedAdvert = (Advert) getLastNonConfigurationInstance();
if (retainedAdvert != null) {
UILApplication.advert = retainedAdvert;
}
}
在哪里UILApplication是单身保持广告。有时(通常当通话摄像头)广告对象erised为默认值。所以我想了解储蓄和kepp这个对象有效的方式。它是明智的,它存储在文件/连载它或单个记录create database或有更好的东西?
Where UILApplication is singleton to keep advert. Sometimes ( often when call camera) advert object is erised to default. So i want to know about save and efficient way to kepp this object. Is it wise to store it in file/ serialise it or create database for a single record or there is something better?
推荐答案
从我的计算器摘自:
@SuppressWarnings("unchecked")
private void loadState() {
ObjectInputStream ois;
try {
ois = new ObjectInputStream(openFileInput(FILE_STATE));
state = ((State) ois.readObject());
ois.close();
ois = new ObjectInputStream(openFileInput(FILE_HISTORY));
historyListAdapter.setItems((List<String>) ois.readObject());
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
state = new State();
} catch (IOException e) {
e.printStackTrace();
state = new State();
} catch (ClassNotFoundException e) {
Toast t = Toast.makeText(this, "Error parsing saved state",
Toast.LENGTH_SHORT);
t.show();
state = new State();
}
setState(state);
}
private void saveState() {
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(openFileOutput(FILE_STATE,
Context.MODE_PRIVATE));
oos.writeObject(state);
oos.close();
oos = new ObjectOutputStream(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();
}
}
@Override
protected void onPause() {
saveState();
super.onPause();
}
呼叫LoadState的()中的onCreate()。
Call loadState() in onCreate().
正常工作对我来说,我知道它不是建议使用Java序列化在Android中,但我没有遇到任何错误或错误任何责任。没有问题,性能无论是。
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.
这篇关于什么是对象存储在Android上最合适的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!