I am creating a To Do List. Right now my app adds and removes data to and from a ListView. However, when I close my application the data gets erased. I want to use SharedPreferences to save the data onDestroy(), then when my app opens I wanted the data to reload.
However, I don't know how to go about accomplishing this task. Can anybody help me with saving a ListView using Shared Preferences (aka I am looking for code)?
There are tutorials for just one shared preference I am looking to dynamically add multiple strings when my application closes. Then when I reopen it, the data will appear. I am only using ONE ACTIVITY page, everything will occur on one page.
HERE IS MY CODE:
public class Main_ToDoList extends Activity implements OnClickListener
{
private Button btnAdd;
private EditText et;
private ListView lv;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
final Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnAdd = (Button)findViewById(R.id.addTaskBtn);
btnAdd.setOnClickListener(this);
et = (EditText)findViewById(R.id.editText);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
// set the lv variable to your list in the xml
lv=(ListView)findViewById(R.id.list);
lv.setAdapter(adapter);
// set ListView item listener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Confirm Delete");
alertDialogBuilder.setMessage("Sure you want to delete?");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
adapter.remove(adapter.getItem(position));
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
dialogInterface.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
public void onClick(View v)
{
String input = et.getText().toString();
if(input.length() > 0)
{
adapter.add(input);
et.setText("");
}
}
@Override
public void onDestroy()
{
super.onDestroy();
}
@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__to_do_list, menu);
return true;
}
}