Dodi
Dodi

Reputation: 2269

Retaining items in a List View

I'm new to android development having some problems. I created a list view that is based on the user input. User has to enter a category in a dialog box and then it's added into the list. Works like a charm. The question is how do I retain those categories once the user exits from an app and starts it again ? When the user starts the app, the list is blank. Do I have to create a preference screen or something to save what the user types ? Here is my code:

public class MainActivity extends Activity {

final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;

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

    lv = (ListView)findViewById(R.id.listView1);
    arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
    lv.setAdapter(arrayAdapter);
}


@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, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()){
    case R.id.menu_add_cat:

        LayoutInflater li = LayoutInflater.from(context);
        View promptAdd = li.inflate(R.layout.prompt_add, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

        //set prompts.xml to alertDialogBuilder
        alertDialogBuilder.setView(promptAdd);

        final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput);

        //set a dialog message
        alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            /*
             *    add a cat here 
             */
                String input = etAddCat.getText().toString();
                if(null != input && input.length() > 0){
                    listItems.add(input);
                    arrayAdapter.notifyDataSetChanged();
                }else{
                    Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();

                }
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
        break;
    }
    //return super.onOptionsItemSelected(item);
    return true;
}

}// end of MainActivity

Upvotes: 0

Views: 579

Answers (2)

Marvin Bernal
Marvin Bernal

Reputation: 902

If the amount of data you want to save is relatively small you can use SharedPreferences to save the String data in your onClick method.

@Override
public void onClick(DialogInterface dialog, int which) {

    String input = etAddCat.getText().toString();
    if(null != input && input.length() > 0){
        listItems.add(input);

        // Add all string data to List<String> listItem
        listItem.add(input);

        arrayAdapter.notifyDataSetChanged();

    }else{
        Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
    }
}

When the user leaves your activity, use the onStop() callback method to save your List<Strings> and store it through SharedPreferences.

@Override
private void onStop() {
    super.onStop();

    SharedPreferences.Editor editor = mSharedPreferences.edit();

    editor.putString(getResources().getString(R.string.list_of_strings), new HashSet<String>(listItem));
    editor.commit;
}

Using the onStart() callback, initialize your List and SharedPreferences. When the user navigates to your activity, your list will be reinitialized when it was saved via onStop().

Finally, iterate through your list, add your items to your ArrayList', create yourArrayAdapter` and set it to your list.

@Override
private onStart(){
    super.onStart();

    SharedPreferences mSharedPreferences;

    mSharedPreferences = this.getApplicationContext().getSharedPreferences("MyPreferences", 0);
    List<String> listItems = new ArrayList<String>(mSharedPreferences.getStringSet("ListOfStrings", null));

    ListIterator li = listItem.listIterator(0);

    while (li.hasNext()) {
        newStatusList.add((String)li.next());
    }

    arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
    lv.setAdapter(arrayAdapter);
}

Upvotes: 0

Wand Maker
Wand Maker

Reputation: 18762

You can save it in SQLite DB, use CursorAdapter for your list view.

Upvotes: 1

Related Questions