Question

Doesn't work saving or reading shared preferences in my service. Could you suggest any workarounds?

Write:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());


    Set<String> set = new HashSet<String>();        
    for (PagerTagGattClient deviceGatt : this){
        set.add(getBluetoothDevice().getAddress());         
    }

    Editor editor = prefs.edit();
    editor.putStringSet(PREF_DEVICES, set);
    return editor.commit();

Read in service onCreate:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Set<String> set = new HashSet<String>();
prefs.getStringSet(PREF_DEVICES, set);

if (set.isEmpty()) Log.e(TAG, "Prefs is empty!"); 

Reading set is always empty.

Was it helpful?

Solution

You need to actually assign the values you read to your variable set:

Change

prefs.getStringSet(PREF_DEVICES, set);

to

set = prefs.getStringSet(PREF_DEVICES, set);

The second parameter is the default value which is an empty HashSet in your case (you can leave it this way or change to an appropriate default value).

OTHER TIPS

try this...

SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
 editor.putStringSet(PREF_DEVICES, set);
editor.commit();

and while reading use

set = prefs.getStringSet(PREF_DEVICES, set);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top