質問

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