这篇文档教你在activity状态改变时如何保存和恢复数据!
上代码PersistentState.java:
public class PersistentState extends Activity
{
/**
* Initialization of the Activity after it is first created. Here we use
* {@link android.app.Activity#setContentView setContentView()} to set up
* the Activity's content, and retrieve the EditText widget whose state we
* will persistent.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See assets/res/any/layout/save_restore_state.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.save_restore_state);
// Set message to be appropriate for this screen.
((TextView)findViewById(R.id.msg)).setText(R.string.persistent_msg);
// Retrieve the EditText widget whose state we will save.
mSaved = (EditText)findViewById(R.id.saved);
}
/**
* Upon being resumed we can retrieve the current state. This allows us
* to update the state if it was changed at any time while paused.
*/
@Override
protected void onResume() {
super.onResume();
SharedPreferences prefs = getPreferences(0);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
if (selectionStart != -1 && selectionEnd != -1) {
mSaved.setSelection(selectionStart, selectionEnd);
}
}
}
/**
* Any time we are paused we need to save away the current state, so it
* will be restored correctly when we are resumed.
*/
@Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.commit();
}
private EditText mSaved;
}
这里使用SharedPreferences类,在pause时存储数据,resume时恢复。
SharedPreferences类是个轻量级的存储类,比文件和数据库方便多了,最适合存储软件参数,当软件退出后,参数还被保留,其实这些数据是存在xml文件中的,在/data/data/<package name>/shared_prefs目录下。
使用起来很简单:
1、使用SharedPreferences保存数据
Editor sharedata = getSharedPreferences("data", 0).edit(); //获取编辑器,产生文件data.xml
sharedata.putString("item","hello getSharedPreferences"); //用编辑器写要保存的数据,第一个参数是id,后面是value
sharedata.commit();//最后提交,切记!!!
2、使用SharedPreferences获取数据
SharedPreferences sharedata = getSharedPreferences("data", 0); //取得data.xml
String data = sharedata.getString("item", null); //取得所需数据