0

I am trying to make a simple todo list app which will probably store only a few things.

After adding items in the ListView, and closing the app, the only entry that loads is the last one that is entered. How do I make all the entered entries show up after closing the app?

Code:

public class MainActivity extends ActionBarActivity {

EditText display;
ListView lv;
ArrayAdapter<String> adapter;
Button addButton;

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

display = (EditText) findViewById(R.id.editText1);
lv = (ListView) findViewById(R.id.listView1);
addButton = (Button) findViewById(R.id.button1);


adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
LoadPreferences();


addButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        String task = display.getText().toString();


            adapter.add(task);
            adapter.notifyDataSetChanged();
            SavePreferences("LISTS", task);
    }
});
}

protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();


}

protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", "None Available");

 adapter.add(dataSet);
 adapter.notifyDataSetChanged();
}}

Thanks in advance.

  • possible duplicate of [Store a List or Set in SharedPreferences](http://stackoverflow.com/questions/6598331/store-a-list-or-set-in-sharedpreferences) – Code-Apprentice Jun 14 '14 at 06:46

2 Answers2

0

You should have to keep key different for each item you are adding to SharedPreferences, otherwise last item you added in preference will override the last one.

maddy d
  • 1,530
  • 2
  • 12
  • 23
0

I won't suggest using SharedPreferences for making an app like a todo list. Make a SQLite database and store your todos in that. Or you can save the todos in a JSON file which is also very simple to achieve.

Using SharedPreferences won't be efficient in this case as you will need to track the keys of all the todo preferences, which creates another overhead.

Check out this post by Lars Vogel about creating content providers and SQLite Databses:

Android SQLite database and content provider - Tutorial

Basant Singh
  • 5,736
  • 2
  • 28
  • 49