Saving data from a ListView using SharedPreferences

I tried to find the answer, but could not find what I was looking for: it was my first attempt to save data / use SharedPreferences, so I was not sure what I was doing. The main thing was that after the user types something into the EditText, he populates the ListView. But I also want the application to save the string when running this application, so that I can use LoadPreferences to use it when the user enters the application again. This does not happen though

code:

public class TaskPage extends SherlockActivity { 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"); } 

I'm sure I did something wrong, but there are no errors. so when I run the application everything works, except that nothing is saved (or maybe it just doesn't appear in the ListView)

So how can I fix this? Thanks!

+4
source share
1 answer

Modify the LoadPreferences () method as follows:

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

in your current code you are not adding dataSet to ArrayAdapter

+3
source

All Articles