如何临时存储对象列表



我有一个对象列表,如果用户最小化应用程序,这些对象需要保留。有没有办法在不使用 SharedPreferences 或 SQLite 数据库的情况下做到这一点(对于单个列表来说似乎有点矫枉过正)?

让对象实现 Parclable 或 Serializable

然后你可以把它放在捆绑包中

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArrayList(key, value);
} 

并根据您的需要将其恢复到onCreate(),onRestoreInstanceState()中。

使用我在这里找到的教程,我使用 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);
   }
}

相关内容

  • 没有找到相关文章

最新更新