[ACCEPTED]-How to iterate through all keys of shared preferences?-sharedpreferences

Accepted answer
Score: 183

What you can do is use getAll() method of SharedPreferences and get 2 all the values in Map<String,?> and then you can easily 1 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.

Score: 9

i think the question has more to do with 14 why

    PreferenceManager.getDefaultSharedPreferences(this).getAll()

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

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

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

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

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

incase anyone wants to iterate through sharedpreferences 1 in KOTLIN

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

In Kotlin is very easey, you can change 1 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)
}

More Related questions