I am succesfully making, saving, and retrieving my shared preferences from my mainActivity
, but I cant get it from my service...
For some reason, my shared preferences is null when I try to retrieve it from a background service...
I initialize my preferences in onCreate:
contactsPrefs = getSharedPreferences("contactsPrefs", MODE_PRIVATE); //Making a shared preferences
Save values in onCreate:
myEditor = contactsPrefs.edit();
Set<String> set = new HashSet<String>();
set.addAll(contactArrayList);
myEditor.clear(); //Clearing current values in shared pref
myEditor.putStringSet("contactSetKey", set); //Adding contacts
myEditor.commit();
All this is going fine, but when I try to access my preferences from my service, I get null:
preferences = PreferenceManager.getDefaultSharedPreferences(c); //See edit at bottom for more info
if(preferences.getStringSet("contactSetKey", null) != null) {
contactArrayList.addAll(preferences.getStringSet("contactSetKey", null));
for (String number : contactArrayList) {
number.substring(number.indexOf("-") + 1); //Remove all characters before the hyphen from my string
Log.v(TAG, number);
}
}else{
Log.v(TAG, "Dagnabit it its null");
}
And to my disappointment, I get the log Dagnabit it its null
. why is it null? I can assure you that it works from my main activity, because I am able to display all of my data from my shared preferences when I access it from my shared preference. So I know that it shouldn't be null...But it is for some reason
Thanks,
Ruchir
EDIT:
I actually register a volume listener using content observer, and I am accesing the preferences from there. Here is in the service:
mSettingsContentObserver = new volumeCheck(this, new Handler());
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver);
Here is the Content Observer:
public class volumeCheck extends ContentObserver {
public volumeCheck(Context c, Handler handler) {
super(handler); //Creates a new handler
context = c; //variable context, defined earlier, is set equal to c, context of service.
preferences = PreferenceManager.getDefaultSharedPreferences(c);
}