iGio90
iGio90

Reputation: 3291

check if sharedpreferences key contains a constant

Since i didn't find anything usefull, or something that reply at my question i would like to know if it's possible to check if a sharedpreference key contains a constant string.

Ex.

Stored on my shared prefs:

<string name="aaa_key1">Value</string>
<string name="aaa_key2">Value</string>
<string name="aaa_key3">Value</string>
<string name="bbb_key1">Value</string>
<string name="bbb_key2">Value</string>
<string name="bbb_key3">Value</string>

I need to add a check so: if prefs contains aaa: do something, if prefs contains bbb: do something else.

Edit for explain: I got some methods on my app that generate sharedpreferences keys+strings based on Users action. All the keys got a constant based on the action executed by the users, so that i need to call some other methods if the keys contains the constant (i.e aaa_key1 or bbb_key1)

Is that possible? Thanks in advance

Upvotes: 0

Views: 731

Answers (2)

Mr_and_Mrs_D
Mr_and_Mrs_D

Reputation: 34026

If you just want separate values no need to get them all - the correct answer in this case is prefs.contains(String)

if (prefs.contains("aaa")
    // aaa
else if (prefs.contains("bbb")
    // bbb

Upvotes: 1

Dev.Sinto
Dev.Sinto

Reputation: 6852

You may find this helpful,to get a list of keys use following method.

What you can do is use getAll() method of SharedPreferences and get all the values in Map 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 info check this original post link

Upvotes: 2

Related Questions