How to save dynamically added items in Listview with sharedpreferences?

不羁的心 提交于 2019-12-24 23:08:25

问题


        protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    preferences = getSharedPreferences(FAVORI, 0);

    ListView favlist = (ListView) findViewById(R.id.favoriliste);

    ArrayList<String> foo = new ArrayList<String>();
    String [] bar = foo.toArray(new String[0]);

    public void favekle(String string) {

    foo.add(string);
    bar = foo.toArray(new String[0]);

    favadapter = new MyFavAdapter(Diziler.this,
            android.R.layout.simple_list_item_1, R.id.txtTitle, bar);
    // favlist= new ArrayList<>();
    favlist.setAdapter(favadapter);
    favadapter.notifyDataSetChanged();

}       
    favadapter = new MyFavAdapter(Diziler.this,
            android.R.layout.simple_list_item_1, R.id.txtTitle, bar);
    // favlist= new ArrayList<>();
    favlist.setAdapter(favadapter);
    favadapter.notifyDataSetChanged();

Hello.I need help.I want save dynamically added items in Listview with SharedPreferences. I'm adding listview items with public void favekle function.I'm adding items to ArrayList<> than i convert ArrayList<> to string array finally i set items to adapter. If i restart application my listview items disappear. How can i save added items with sharedpreferences?I used StringBuilder but it didn't work.Thank you.


回答1:


You can save to shared preference in this way

SharedPreferences sp = context.getSharedPreferences(
            "file name", 0);
    SharedPreferences.Editor spEdit = sp.edit();
    spEdit.putLong(key, value);
    spEdit.commit();



回答2:


You are supposed to store single key-value paired data with SharedPreferences. Trying to store big grouped data is not efficient at all. You should use an SQLite database.

SQLite and ContentProvider Tutorial




回答3:


You can store string sets in Shared Preferences, then convert them back to a List when you retrieve them.

ArrayList<String> list = new ArrayList<String>();
list.add("test1");
list.add("test2");

PreferenceManager.getDefaultSharedPreferences(context)
    .edit()
    .putStringSet("stringset", new HashSet<String>(list))
    .commit();


来源:https://stackoverflow.com/questions/23830957/how-to-save-dynamically-added-items-in-listview-with-sharedpreferences

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