How to iterate through all keys of shared preferences?

AndroidSharedpreferences

Android Problem Overview


SharedPreferences have method getAll, but it returns no entries despite the fact some keys exist:

PreferenceManager.getDefaultSharedPreferences(this).contains("addNewAddress");

returns true

Map<String, ?> keys=PreferenceManager.getDefaultSharedPreferences(this).getAll();

returns empty map

What is wrong? How to get list of all shared preferences?

Android Solutions


Solution 1 - Android

What you can do is use getAll() method of SharedPreferences and get all the values in Map<String,?> and then you can easily iterate through.

Map<String,?> keys = prefs.getAll();

for(Map.Entry<String,?> entry : keys.entrySet()){
            Log.d("map values",entry.getKey() + ": " + 
                                   entry.getValue().toString());            
 }

For more you can check PrefUtil.java's dump() implementation.

Solution 2 - Android

i think the question has more to do with why

    PreferenceManager.getDefaultSharedPreferences(this).getAll()

is returning an empty/contradictory map than with how to iterate over a standard java map. the android doc isn't really crystal clear about what's going here but basically it seems like the first call ever to

    PreferenceManager.setDefaultValues(this, R.xml.preferences,false)

-- which is what you're supposed to call to initialize preferences when you start your app -- creates some kind of cached version of your preferences which causes future changes to your xml preferences file to be inconsistently handled, i.e., causing the mismatch you described in your question.

to reset this "cached entity", follow these steps (which you can sort of come up with from the above link):

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.edit().clear();
	PreferenceManager.setDefaultValues(this, R.xml.preferences, true);

Solution 3 - Android

incase anyone wants to iterate through sharedpreferences in KOTLIN

 sharedPreferences?.all?.forEach {
     //access key using it.key & value using it.value
     Log.d("Preferences values",it.key() + ": " + it.value()             
 }

Solution 4 - Android

In Kotlin is very easey, you can change FILE_PREF_XML for you preferences file

getSharedPreferences("FILE_PREF_XML", Context.MODE_PRIVATE).all?.forEach {
    Log.d(TAG,"shared pref(" + it.key + ") = " + it.value)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEugene ChumakView Question on Stackoverflow
Solution 1 - AndroidLalit PoptaniView Answer on Stackoverflow
Solution 2 - AndroidrmannaView Answer on Stackoverflow
Solution 3 - Androidanoo_radhaView Answer on Stackoverflow
Solution 4 - AndroidWebserveisView Answer on Stackoverflow