Saving Data from ListView using SharedPreferences

点点圈 提交于 2021-02-18 13:51:37

问题


i tried searching for an answer but could not find what i was looking for: this was my first try at saving data/using SharedPreferences so i wasnt quite sure of what i was doing. The main point was so that after a user inputs something in the EditText, it populates the ListView. But i also want it so that when this is carried out, the app also saves the string so that I can use LoadPreferences to have it when a user re-enters the app. This does not happen though

the 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");

}

Im quite sure that i did something wrong but there are no errors. so when i run the app, everything works except nothing is saved(or maybe it just does not show in the ListView)

So how can i fix this? Thanks!


回答1:


Change you LoadPreferences() method as :

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



来源:https://stackoverflow.com/questions/14175313/saving-data-from-listview-using-sharedpreferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!