Why, in androidx settings/preferences, am I getting "java.lang.String cannot be cast to java.lang.Integer" exception?

24 Views Asked by At

In my preferences.xml I have this:

        <ListPreference
           app:dependency="@string/auto_record_key"
           app:defaultValue="3"
           app:dialogTitle="@string/track_step_distance_dialog_title"
           app:entries="@array/track_step_distance_entries"
           app:entryValues="@array/track_step_distance_values"
           app:key="@string/track_step_distance_key"
           app:summary="@string/track_step_distance_summary"
           app:title="@string/track_step_distance_title" />

with these arrays:

        <item>off (time only)</item>
        <item>5</item>
        <item>10</item>
        <item>15</item>
        <item>20</item>
        <item>30</item>
        <item>50</item>
        <item>100</item>
        <item>200</item>
        <item>300</item>
    </string-array>

    <string-array name="track_step_distance_values">
        <item>0</item>
        <item>5</item>
        <item>10</item>
        <item>15</item>
        <item>20</item>
        <item>30</item>
        <item>50</item>
        <item>100</item>
        <item>200</item>
        <item>300</item>
    </string-array>

In my onSharedPreferenceChanged:

        keyString = mContext.getString(R.string.track_step_distance_key );
        if (  key == null || key.equals( keyString )  ) {
        int trackStepDistance = preferences.getInt( keyString, 3 ); 
        }

Whenever this onSharedPreferenceChanged code runs, it gets this exception:

        java.lang.RuntimeException: Unable to start activity ComponentInfo{dkr.ajijic.apps.tracks/dkr.ajijic.apps.tracks.MySettingsActivity}: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

Why?

1

There are 1 best solutions below

0
BinCodinLong On

Your

     int trackStepDistance = preferences.getInt( keyString, 3 );

gets the exception because the preferences library does something deceptive. You reasonably assumed that the array:

        <string-array name="track_step_distance_values">
        <item>0</item>
        <item>5</item>
        <item>10</item>
        <item>15</item>
        <item>20</item>
        <item>30</item>
        <item>50</item>
        <item>100</item>
        <item>200</item>
        <item>300</item>
    </string-array>

tells the library to send integers to the sharedPreferences file. But the library doesn't do that; it sends Strings. So, getInt is trying to get an integer from a string, and that causes the exception. The fix?

    int trackStepDistance = Integer.parseInt(preferences.getString( keyString, "6" ));

Now we're properly getting the String, and then parsing it to integer.