javaandroidlistpreferencegetvalue

ListPreference, get value from fragment


My app contains a listPreference with entries and an entryValues list in my strings.xml

I want to receive the value of the currently selected entry in a PreferenceFragment.

Right now, I use the following code to fetch these values, (and later on, convert the string into an integer to uuse it for an URL that depends on variables).

 @Nullable
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            myView = inflater.inflate(R.layout.first_layout, container, false);


ListPreference lP = (ListPreference) findPreference("example_list");
String currValue = lP.getValue();

int aktuelleklasse = Integer.valueOf(currValue);


return myView;
}

unfortunately, I get an error, saying

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.preference.ListPreference.getValue()' on a null object reference

So what do I need to do to get my value withouut error? (I've got quite basic skills so dont judge me, if thats an obvious problem :))

Thanks in advance!


Solution

  • Are you doing a addPreferencesFromResource(R.xml.preferencesFile) before this code section?
    See PreferenceFragment.findPreference always returns NULL