简体   繁体   English

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

[英]How to store data in an ArrayList in Java

I am building an android app and I am having trouble with an ArrayList. 我正在构建一个Android应用程序,但遇到了ArrayList问题。 I am using it to store strings and then putting those strings into a list. 我使用它来存储字符串,然后将这些字符串放入列表中。 I can add new items to the ArrayList no bother but if I go to a new activity and go back to this list the items are gone. 我可以轻松地将新项目添加到ArrayList中,但是如果我转到一个新活动并返回到此列表,则这些项目都消失了。 How can I stop this happening? 我该如何阻止这种情况发生?

Here is the MainListActivity: 这是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");
}

}

Thanks, John 谢谢,约翰

One way of doing this would be to store your array using SharedPreferences. 一种方法是使用SharedPreferences存储数组。

  1. In your MainActivity class, declare file for preferences: 在您的MainActivity类中,声明用于首选项的文件:

     public static final String PREF_FILE = "preferences"; 
  2. Override onPause(), where we will save ArrayList: 覆盖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. Override onResume(), and restore the list: 覆盖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); } } 

A couple of things to remember: 需要记住的几件事:

  • this solution requires you to use API 11+ (putStringSet() was added in API 11) 此解决方案要求您使用API​​ 11+(在API 11中添加了putStringSet())
  • Set contains NO duplicates, so take that into account 集合中没有重复项,因此请考虑到这一点

override the saveInstanceState(bundle) method in your activity and save it the the bundle and later receive it from the onCreate(bundle). 在您的活动中重写saveInstanceState(bundle)方法,并将其保存为捆绑包,然后从onCreate(bundle)接收它。 the parameter bundle for onCreate() is passed by the system and contains what you have saved in the saveinstanceState() method. 系统将传递onCreate()的参数包,其中包含您在saveinstanceState()方法中保存的内容。

You can always use a Singleton to hold cross activity data without messing with the Activity lifecycle. 您始终可以使用Singleton来保存交叉活动数据,而不会弄乱Activity的生命周期。

I do it every now and then without performance issues or drawback and I find more elegant and less error prone that handlig the different onXXX method of the activity. 我时不时地这样做,而没有性能问题或缺点,我发现更优雅,更不容易出错,这使该活动的不同onXXX方法变得容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM