如何在Java中的ArrayList中存储数据

时间:2013-12-28 19:31:47

标签: java android arraylist

我正在构建一个Android应用程序,我遇到了一个ArrayList问题。我用它来存储字符串,然后将这些字符串放入列表中。我可以添加新的项目到ArrayList没有麻烦,但如果我去一个新的活动并返回到这个列表项目已经消失。我该如何阻止这种情况发生?

这是MainListActivity:

public class MainListActivity extends FragmentActivity implements NewListItemDialog.NewListItemDialogListener {

List<String> mListItems = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_list);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
             android.R.layout.simple_list_item_1, mListItems);
    ListView lv = (ListView) findViewById(android.R.id.list);
    lv.setAdapter(adapter); 

    lv.setOnItemClickListener(new OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
              Intent matrixIntent = new Intent(getApplicationContext(), MatrixDetailActivity.class);
              startActivity(matrixIntent);
          }
        });
}

@Override
public void onDialogPositiveClick(DialogFragment dialog) {

    Dialog dialogView = ((DialogFragment) dialog).getDialog();
    EditText newListItemName = (EditText) dialogView.findViewById(R.id.newListItemName);
    mListItems.add(newListItemName.getText().toString());
    Toast.makeText(this, newListItemName.getText().toString() + " has been added", Toast.LENGTH_LONG).show();
    dialog.dismiss();

}

@Override
public void onDialogNegativeClick(DialogFragment dialog) {        

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_list, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    switch (item.getItemId()) {
    case R.id.new_list_item:
        showNewListItemDialog();
        break;
    }
    return true;
}

public void showNewListItemDialog() {
    FragmentManager fm = getSupportFragmentManager();
    NewListItemDialog newListItemDialog = new NewListItemDialog();
    newListItemDialog.show(fm, "NewListItemDialog");
}

}

谢谢, 约翰

3 个答案:

答案 0 :(得分:1)

这样做的一种方法是使用SharedPreferences存储您的数组。

  1. 在MainActivity类中,为首选项声明文件:

    public static final String PREF_FILE = "preferences";
    
  2. 覆盖onPause(),我们将保存ArrayList:

    @Override
    protected void onPause() {
        super.onPause();
    
        //create preferences and get editor, so that we can insert and save our array
        SharedPreferences preferences = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
    
        //convert ArrayList to set so that it can be stored
        //NOTE: putStringSet() was added in API 11
        Set<String> stringSet = new HashSet<String>(list);
    
        //place the set under the key 'mylist'
        editor.putStringSet("mylist", stringSet);
    
        //save it
        editor.commit();
    }
    
  3. 覆盖onResume(),并恢复列表:

    @Override
    protected void onResume() {
        super.onResume();
    
        SharedPreferences preferences = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
    
        //get saved set, set to null if no set present
        Set<String> set = preferences.getStringSet("mylist", null);
    
        //if set is != null recreate ArrayList and assign to list variable
        //set will be null on first run, because onPause() have not yet been called
        //to save the array, hence we need to do this check 
        if (set != null) {
            list = new ArrayList<String>(set);
        }
    }
    
  4. 要记住几件事:

    • 此解决方案要求您使用API​​ 11+(在API 11中添加putStringSet())
    • 设置包含NO重复项,因此请将其考虑在内

答案 1 :(得分:0)

覆盖活动中的saveInstanceState(bundle)方法并将其保存为bundle,然后从onCreate(bundle)接收它。 onCreate()的参数包由系统传递,包含你在saveinstanceState()方法中保存的内容。

答案 2 :(得分:0)

您始终可以使用Singleton来保存交叉活动数据,而不会影响活动生命周期。

我时不时地执行此操作而没有性能问题或缺点,并且我发现更加优雅且不易出错,因此可以使用不同的onXXX活动方法。