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.

有帮助吗?

解决方案

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

其他提示

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top