如果用户最小化应用程序,我有一个需要保留的对象列表。有没有办法在不使用 SharedPreferences 或 SQLite 数据库的情况下做到这一点(对于单个列表来说似乎有点矫枉过正)?
问问题
898 次
2 回答
2
让对象实现Parclable或Serializable
然后你可以把它放在Bundle中
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(key, value);
}
并根据您的需要在 onCreate(),onRestoreInstanceState() 中取回它。
于 2013-02-01T00:10:14.450 回答
1
使用我在这里找到的教程,我使用 SharedPreferences 实现了它,主要区别在于我使用索引而不是使用键“MEM1”。当我的活动加载时,我可以使用此代码检查索引的大小,
for(int x =0; ;x++) {
index = x;
if(sharedPreferences.contains(String.valueOf(x))){
temp = gson.fromJson(sharedPreferences.getString(String.valueOf(x), null), PointOfInterest.class);
pointList.add(temp);
}
else {
break;
}
}
例子:
public class AndroidSharedPreferencesEditor extends Activity {
EditText editText1, editText2;
TextView textSavedMem1, textSavedMem2;
Button buttonSaveMem1, buttonSaveMem2;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textSavedMem1 = (TextView)findViewById(R.id.savedmem1);
textSavedMem2 = (TextView)findViewById(R.id.savedmem2);
editText1 = (EditText)findViewById(R.id.edittext1);
editText2 = (EditText)findViewById(R.id.edittext2);
buttonSaveMem1 = (Button)findViewById(R.id.save_mem1);
buttonSaveMem2 = (Button)findViewById(R.id.save_mem2);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
buttonSaveMem2.setOnClickListener(buttonSaveMem2OnClickListener);
LoadPreferences();
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
LoadPreferences();
}
};
Button.OnClickListener buttonSaveMem2OnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM2", editText2.getText().toString());
LoadPreferences();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}
于 2013-02-01T15:07:21.087 回答