sharedPref.getInt: java.lang.String cannot be cast to java.lang.Integer

后端 未结 3 1244
孤街浪徒
孤街浪徒 2021-01-02 23:12

I have a preferences.xml which contains the following definition:



        
相关标签:
3条回答
  • 2021-01-02 23:47

    First let's have a look at SharedPreferences.getInt() method.

    public abstract int getInt (String key, int defValue)

    • Added in API level 1
    • Retrieve an int value from the preferences.

    Parameters

    1. key : The name of the preference to retrieve.
    2. defValue : Value to return if this preference does not exist.

    Returns : Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not an int.

    So in your case, all the entry values have been defined as a string array. Therefore the class cast exception will be thrown.

    You can simply solve this problem by modifying your code as follows.

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    int offsetProgressInitial = Integer.parseInt(sharedPref.getString("limitSetting", "10"));
    
    0 讨论(0)
  • 2021-01-02 23:53

    If you look at what getInt() does internally you will see the problem:

    Integer v = (Integer)mMap.get(key);
    

    Your key "limitSetting" is returning a String which cannot be cast to an Integer.

    You can parse it yourself however:

    int offsetProgressInitial = Integer.parseInt(sharedPref.getString("limitSetting", "10"));
    
    0 讨论(0)
  • 2021-01-03 00:07

    The problem is that if putInt was never called then getInt will return a null value, even if you set a default integer value.

    This seems to be a bug that was never fixed. So the solution is to call the putInt before calling getInt.

    0 讨论(0)
提交回复
热议问题