简体   繁体   中英

Trying to update shared preference from a Fragment Activity

I'm building a custom ringtone selector for my app. The class is called SoundPicker and it extends FragmentActivity . What I'm trying to do is save the selected ringtone to my app's settings file.

Here is my code:

String selectedResource = "blablabla";
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet("notifications_new_message", selectedResource);
editor.commit();

The problem is that I get an error, refering to the new string I'm trying to set - selectedResource

That's the error I get:

Wrong 2nd argument type. Found: 'java.lang.String', required: 'java.util.Set'

putStringSet (String, java.util.Set) in Editor cannot be applied to (String, java.lang.String)

What am I doing wrong here? Thank you!

Please be careful, putString and putStringSet is different method, so use putString instead

editor.putString("notifications_new_message", selectedResource);

You are trying to set string but putStringSet accept 2nd argument of type set

use putString to store string value or create string set and use putStringSet

//To store string value
String selectedResource = "blablabla";
SharedPreferences sharedPref = 
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("notifications_new_message", selectedResource);
editor.commit();



//To Store string set
Set<String> hs = ss.getStringSet("set", new HashSet<String>());

String selectedResource = "blablabla";

hs.add(selectedResource);

SharedPreferences sharedPref =         
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet("notifications_new_message", hs);
editor.commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM