SharedPreferences values not retrieved from a service when called from another activity that created them
Good day, am having a quite baffling problem and its supposed to be pretty much straightforward. i have this 3 class:
1.A config activity that creates and saves sharedpreferences.
2.A service.
3.Another Activity B
From the Config Activity, i save in this manner:
prefs = getSharedPreferences(MY_PREF_NAME, MODE_WORLD_READABLE);
boolean toggleCheck = toggleCelsius.isChecked();
boolean currentLocation = mylocation.isChecked();
boolean searchLocation = search.isChecked();
int updateSet = update.getSelectedItemPosition();
Editor editor = prefs.edit();
editor.putString(CITY + appWidgetId, city);
editor.putBoolean(GPS_LOCATION + appWidgetId, currentLocation);
editor.putBoolean(SEARCH_LOCATION + appWidgetId, searchLocation);
editor.putBoolean(CHECKED_CELSIUS + appWidgetId , toggleCheck);
editor.putInt(REFRESH_UPDATE + appWidgetId, updateSet);
editor.commit();
and i retrieve from the service onCreate() Method this way:
SharedPreferences prefs = this.getSharedPreferences(myCastConfigure.MY_PREF_NAME, MODE_WORLD_READABLE); //have tried using getApplicationContext()
city = prefs.getString(CITY + appWidgetId,"nothing");
chk_celsius = prefs.getBoolean(CHECKED_CELSIUS + appWidgetId, true);
updateRate = Configure.convertToMillis(prefs.getInt(REFRESH_UPDATE + appWidgetId, 1));
After i save the preferences, the service starts and i can retrieve the sharedPreferences Value from the service.But when i try to restart the service from the Activity B, i don't retrieve the sharedpreference value from the service anymore. instead i get the value "nothing". I have tried using getApplicationContext() from the service, but that doesn't seem to he开发者_C百科lp too! can anybody please explain whats going on and give suggestions. Thank you.
You are not saving and reading the same key:
editor.putString(CITY, city);
prefs.getString(CITY + appWidgetId,"nothing");
You save CITY but read CITY + appWidgetId
Ok, finally I have found the solution. The problem is, I think, that your service is running in a different process.
<service
android:name="servicename"
android:process=":my_process" > --> option1: delete this
</service>
and sharedpreferences are not supported in different services... you can do 2 things. The first is, to run the service on the main thread, or set MODE_MULTI_PROCESS
when calling getSharedPreferences()
.
Better late then never :)
精彩评论