Search code examples
androidsharedpreferencesandroid-preferencespreferenceactivity

android preference getString returning null value


I have an android preference screen with list preference of language selection as

 <ListPreference
   android:key="prefLanguage"
   android:entries="@array/langPref"
   android:summary="@string/pref_set_lang_summary"
   android:entryValues="@array/langPrefValues"
   android:title="@string/pref_set_language"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:defaultValue="1" />

I am trying to get the preference value within the oncreate action as

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String langPref = sharedPrefs.getString("langPrefValues", "NULL");

Log.i("MyActivity",langPref);

But the logcat shows the null value to MyActivity string.


Solution

  • You are currently trying to get the preference value with the name of the entryValues array langPrefValues and that is not a valid preference value.

    You should instead use the preference key to get the current preference value which is prefLanguage in the xml provided.

    String langPref = sharedPrefs.getString("prefLanguage", "NULL");