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.

Était-ce utile?

La 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).

Autres conseils

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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top