Question

I am trying to get the value after the it is selected in setting preferences dialog. But I get a ClassCastException and a crash? Probably because I'm not sure how to get the value that has been selected and save it. Essentially I need to be able to get the new value in another Activity. How do you get these values and save and be able to find them in other activities?

 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

        SharedPreferences s = getSharedPreferences("MY_PREFS", 0);

        // Create a editor to edit the preferences:
        SharedPreferences.Editor editor = s.edit();

 if (key.equals("language_key")) {

       sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
       ListPreference listPref = (ListPreference) sharedPreferences; 
       String entryvalue = (String) listPref.getEntry();

        if (entryvalue == "EN")
        {
            Log.d(TAG, "EN" + entryvalue);
            Toast.makeText(getBaseContext(), "true", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Log.d(TAG, "else" + entryvalue);
            Toast.makeText(getBaseContext(), "false", Toast.LENGTH_SHORT).show();
            }



       }
}

preferences xml file

<ListPreference 
            android:key="language_key"
            android:summary="Choice of language mode"
            android:title="Language Mode"
            android:defaultValue="CH"
            android:entries="@array/Languages"
        android:entryValues="@array/LanguageValues"   /> 

array.xml

<string-array name="Languages">
    <item name="EN">English</item>
    <item name="CH">Chinese</item>
    <item name="SP">Spanish</item>
</string-array>

<string-array name="LanguagesValues">
    <item name="EN">EN</item>
    <item name="CH">CH</item>
    <item name="SP">SP</item>
</string-array>
Was it helpful?

Solution

sharedPreferences can't be casted to ListPreferences. For getting value, invoke getString method:

sharedPreferences.getString( "language_key", "");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top