Reputation:
I try to access SharedPreferences inside Service. But when it's started first time and I try to read preferences, I get only default values, as if preferences don't exist. But after I open my preference Activity at first time, Service gets values. Is that normal?
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="CATEGORY_UPDATE"
android:title="@string/autoUpdateCategory_title">
<CheckBoxPreference
android:key="PREF_AUTO_UPDATE"
android:title="@string/preferences_autoUpdate_title"
android:summary="@string/preferences_autoUpdate_summary"
android:defaultValue="true">
</CheckBoxPreference>
<ListPreference
android:key="PREF_UPDATE_FREQ"
android:title="@string/preferences_updateFreq_title"
android:summary="@string/preferences_updateFreq_summary"
android:dialogTitle="@string/preferences_updateFreq_title"
android:entryValues="@array/updateFreq_values"
android:entries="@array/updateFreq_options"
android:defaultValue="30">
</ListPreference>
</PreferenceCategory>
</PreferenceScreen>
public class Preferences extends PreferenceActivity {
public static final String PREF_AUTO_UPDATE = "PREF_AUTO_UPDATE";
public static final String PREF_UPDATE_FREQ = "PREF_UPDATE_FREQ";
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
/* INSIDE SERVICE */
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean autoUpdate =
prefs.getBoolean(Preferences.PREF_AUTO_UPDATE, false);
int updateFreq =Integer.parseInt(prefs.getString(Preferences.PREF_UPDATE_FREQ, "0"));
During first Service launch I get 0 and false, despite default values. And after going to preference Activity everything is ok.
Upvotes: 0
Views: 365
Reputation: 30168
I'm pretty sure the default values provided in the XML are meant for the UI, not for creating a "default preferences file". If you want your default values to be returned when your preferences file has not been created yet, just retrieve them specifying the values you want:
boolean autoUpdate =
prefs.getBoolean(Preferences.PREF_AUTO_UPDATE, true);
int updateFreq =Integer.parseInt(
prefs.getString(Preferences.PREF_UPDATE_FREQ, "30"));
Upvotes: 1
Reputation: 8242
normal behavious is once you committed into sharedPreferences , You can always read it later , no matter whether from activity or a service .
Possible issue here might be
1) Yor are clearing your preferences somewhere , den re-inserting preference into activity ,so now service can read it . or
2) Preference name is not matching .
Upvotes: 0