androidnullcrashlistpreferencepreferencescreen

PreferenceScreen default settings during first run


Good day,

I have a problem - I have a PreferenceScreen with a ListPreference that has default values. Then, I have an Activity that gets a value from that ListPreference, but it returns "null" if I do not open PreferenceScreen first.

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    String prefSize = sp.getString("size", null);
    Size = Integer.parseInt(prefSize);
    mySize = Size;

Is it possible to do something about it? If I open my PreferenceScreen and then go to the activity it returns the default value, but if I open my Activity during the first run before I open the PreferenceScreen (just open, not changing any setttings) it the app crashes.

Thank you so much!


Solution

  • try this

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    String prefSize = sp.getString("size", "1");//provide deafult values to parse into int for first time
    Size = Integer.parseInt(prefSize);
    mySize = Size;