Brian Le
Brian Le

Reputation: 159

Accessing shared preferences not working correctly

I have this piece of code that stores a "toggle" for a specific item on a listview. I use the item's name as the key. However, the result of getBoolean always returns the default value specified in the second parameter. I can't really figure out if I implemented it wrong, or I am overlooking something
For clarification, summonerNames is an arraylist of Strings.

        MenuItem toggle = menu.findItem(R.id.postGameNotif);
        SharedPreferences prefs = getApplicationContext().getSharedPreferences("summoner_prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        Log.i(TAG, summonerNames.get(position));
        boolean postNotif = prefs.getBoolean(summonerNames.get(position),false);
        if (postNotif == true) {
            toggle.setTitle("Disable post-game notifications");
            Log.i(TAG,"Disabled");
            editor.putBoolean(summonerNames.get(position), false);
        }
        else {
            toggle.setTitle("Enable post-game notifications");
            Log.i(TAG, "Enabled");
            editor.putBoolean(summonerNames.get(position), true);
            Log.i(TAG, String.valueOf(prefs.getBoolean(summonerNames.get(position),false)));
        }

Upvotes: 0

Views: 688

Answers (1)

user1140237
user1140237

Reputation: 5045

Issue is added values are not committed in shared preference.

After addedin boolean value you missed to commit changes in sharedpreference

Check this link

 MenuItem toggle = menu.findItem(R.id.postGameNotif);
        SharedPreferences prefs = getApplicationContext().getSharedPreferences("summoner_prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        Log.i(TAG, summonerNames.get(position));
        boolean postNotif = prefs.getBoolean(summonerNames.get(position),false);
        if (postNotif == true) {
            toggle.setTitle("Disable post-game notifications");
            Log.i(TAG,"Disabled");
            editor.putBoolean(summonerNames.get(position), false);
editor.commit()// you need to commit after adding it to sharedpref
        }
        else {
            toggle.setTitle("Enable post-game notifications");
            Log.i(TAG, "Enabled");
            editor.putBoolean(summonerNames.get(position), true);
editor.commit()// you need to commit after adding it to sharedpref
            Log.i(TAG, String.valueOf(prefs.getBoolean(summonerNames.get(position),false)));
        }

Upvotes: 3

Related Questions