Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences putStringSet doesn't work [duplicate]

I need to put Set in SharedPreference, but I have a problem.

when I click button, I will get Set from SharedPreference and add data to Set then put back SharedPreference, but when I destroy project and open it again, the sharedPreference only get one string in Set

SharedPreferences s = getSharedPreferences("db", 0);
Log.i("chauster", "1.set = "+s.getStringSet("set", new HashSet<String>()));

Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new Button.OnClickListener() {

    @Override
    public void onClick(View v) {
        SharedPreferences ss = getSharedPreferences("db", 0);
        Set<String> hs = ss.getStringSet("set", new HashSet<String>());
        hs.add(String.valueOf(hs.size()+1));
        Editor edit = ss.edit();
        edit.putStringSet("set", hs);
        edit.commit();
        SharedPreferences sss = getSharedPreferences("db", 0);
        Log.i("chauster", "2.set = "+sss.getStringSet("set",
                new HashSet<String>()));
    }
});

when I install project first, and I click button 4 times, the logcat print it

1.set = []
2.set = [1]
2.set = [2, 1]
2.set = [3, 2, 1]
2.set = [3, 2, 1, 4]

it's look like success to put string in sharedPreference Set, but when I destroy app and open it again, the logcat print it

1.set = [1]

it means only one string in Set from sharedPreference, I don't know what's happened? Please help me. thanks~

like image 480
henry4343 Avatar asked Jan 28 '14 03:01

henry4343


1 Answers

You fell to the usual trap of editing the value you got from getStringSet(). This is forbidden in the docs

You should :

SharedPreferences ss = getSharedPreferences("db", 0);
Set<String> hs = ss.getStringSet("set", new HashSet<String>());
Set<String> in = new HashSet<String>(hs);
in.add(String.valueOf(hs.size()+1));
ss.edit().putStringSet("set", in).commit(); // brevity
// SharedPreferences sss = getSharedPreferences("db", 0); // not needed
Log.i("chauster", "2.set = "+ ss.getStringSet("set", new HashSet<String>()));

For a half baked explanation see : Misbehavior when trying to store a string set using SharedPreferences

like image 106
Mr_and_Mrs_D Avatar answered Nov 06 '22 08:11

Mr_and_Mrs_D