John McDonald
John McDonald

Reputation: 71

How to store data in an ArrayList in Java

I am building an android app and I am having trouble with an 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. How can I stop this happening?

Here is the 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

Upvotes: 0

Views: 1798

Answers (3)

Melquiades
Melquiades

Reputation: 8598

One way of doing this would be to store your array using SharedPreferences.

  1. In your MainActivity class, declare file for preferences:

    public static final String PREF_FILE = "preferences";
    
  2. Override onPause(), where we will save 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:

    @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)
  • Set contains NO duplicates, so take that into account

Upvotes: 1

elbuild
elbuild

Reputation: 4899

You can always use a Singleton to hold cross activity data without messing with the Activity lifecycle.

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.

Upvotes: 0

Niraj Adhikari
Niraj Adhikari

Reputation: 1728

override the saveInstanceState(bundle) method in your activity and save it the the bundle and later receive it from the onCreate(bundle). the parameter bundle for onCreate() is passed by the system and contains what you have saved in the saveinstanceState() method.

Upvotes: 0

Related Questions