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

标签 java android arraylist

我正在构建一个 Android 应用程序,但在使用 ArrayList 时遇到了问题。我用它来存储字符串,然后将这些字符串放入列表中。我可以毫不费力地将新项目添加到 ArrayList,但如果我转到新 Activity 并返回到此列表,项目就会消失。我怎样才能阻止这种情况发生?

这是 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");
}

}

谢谢, 约翰

最佳答案

实现此目的的一种方法是使用 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);
        }
    }
    

需要记住的几件事:

  • 此解决方案要求您使用 API 11+(putStringSet() 已在 API 11 中添加)
  • 集合不包含重复项,因此请考虑到这一点

关于java - 如何在Java中将数据存储在ArrayList中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20818500/

相关文章:

java - 为什么带有两个 Jpanel 的父 Jpanel 不只显示第一个 Show 本身而不显示其两个子 Jpanels?

java - 如何将 web3j 库加载到 sbt 项目?

android - Realm 一对多关系不持久

java - ArrayList 到字符串数组

java - 在错误地猜测 ArrayList 容量与未使用的值之间进行权衡?

java - 按降序或升序排列日期的 ArrayList

java注释不调用重写的方法

java - 蛇游戏程序-制作蛇的 body

android原生发送按钮图标

android - 通过应用内购买支付的 Google Play 订单无法收取费用