문제

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