0

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

iGio90
  • 3,251
  • 7
  • 30
  • 43
  • 1
    I think you are refering to sharedpreferences the wrong way. you could refer to this as a sample code: https://github.com/rakeeb11/simple-shared-preferences ... its always easier when you set sharedpreference in a separate class. – Rakeeb Rajbhandari Dec 19 '13 at 06:10
  • Nono, i'm refering it right... i got some method on my app that store sharedprefrences based on strings generated from users action. These strings got a constant at first so that i need to check if the strings stored got this constant and execute some other methods – iGio90 Dec 19 '13 at 06:13
  • when saving to sharedpreferences haven't you used any keys to identify them values? Because with sharedpreferences you ought to assign keys. – Rakeeb Rajbhandari Dec 19 '13 at 06:16

2 Answers2

2

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

Community
  • 1
  • 1
Dev.Sinto
  • 6,802
  • 8
  • 36
  • 54
1

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
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361