Search code examples
androidandroid-sharedpreferences

SharedPreferences is being reset every time the app started


I have this code on my MainActivity.java:

  SharedPreferences ids = getSharedPreferences(AddedIds, Context.MODE_PRIVATE);
  SharedPrefernces.Editor editor = ids.edit();
    if (ids.getStringSet(AddedIds, id).isEmpty()) {
        Set<String> id = new HashSet<String>();
        editor.putStringSet(AddedIds, id);
        editor.apply();
    }

This code is checking whether the Set<String> is existing in the SharedPreferences. If not, then it adds the Set<String> to the SharedPreferences.

The problem is that the code is being activated whenever I open the app, althrough it exist in the SharedPreferences.


Solution

  • I believe id is the string that you are searching in stringset. Change your code to below.

    Set<String> set = ids.getStringSet(AddedIds, null);
        Boolean keyfound = false;
        if ( set != null){
            for (String key : set){
                if(key.equals(id)){
                    keyfound = true;
                    break;
                }
            }
            if(!keyfound){
                set.add(id);
                editor.putStringSet(AddedIds, set);
                editor.apply();
            }
        }
        else{
            set = new HashSet<String>();
            set.add(id);
            editor.putStringSet(AddedIds, set);
            editor.apply();
        }