Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a ClassCastException: java.lang.Integer cannot be cast to java.lang.String error without casting

I am working on an app for Android and can't figure out the error or mistake which I am making. I am searching for the error for more than 4 hours.

I am getting the following Exception working with SharedPreferences:

E/AndroidRuntime: FATAL EXCEPTION: main
   Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
     at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:235)
     at de.immozukunft.quicksteuer.QuickSteuerActivity.updateTextView(QuickSteuerActivity.java:56)
     at de.immozukunft.quicksteuer.QuickSteuerActivity.onCreate(QuickSteuerActivity.java:36)

But I am not doing a cast in that line according to my understanding. Line 36 is the call of the method updateTextView().

private void updateTextView() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    int legalForm = Integer.parseInt(prefs.getString("legal_form", "1"));
    boolean industrialTax = prefs.getBoolean("industrial_tax", false);
    boolean turnoverTax = prefs.getBoolean("turnover_tax", false);
    boolean disbursal = prefs.getBoolean("disbursal", false);

    String tmp = prefs.getString("capitalownership", "0"); //this is line 56

    int capitalOwnership = Integer.parseInt(tmp);
    int estIncome = Integer.parseInt(prefs.getString("est_income", "0"));
}

My preference in the XML-File is the following:

<EditTextPreference
android:defaultValue="0"
android:dialogTitle="@string/capitalownership"
android:inputType="number"
android:key="capitalownership"
android:title="@string/capitalownership" />

I needed I will post the full code and full Error list.

I am relatively new to Android.

Solution

    private void updateTextView() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    String legalForm = prefs.getString("legal_form", "1");
    boolean industrialTax = prefs.getBoolean("industrial_tax", false);
    boolean turnoverTax = prefs.getBoolean("turnover_tax", false);
    boolean disbursal = prefs.getBoolean("disbursal", false);
    String capitalOwnership = prefs.getString("capitalownership", "0");
    String estIncome = prefs.getString("est_income", "1");

    settingstv.setText(getString(R.string.overview_settings,
            legalForm,
            Boolean.toString(industrialTax),
            Boolean.toString(turnoverTax),
            Boolean.toString(disbursal),
            capitalOwnership,
            estIncome));

    try {
        if (!compareCurrentWithStoredVersionCode(this, prefs, "storedVersionCode")) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("legal_form", legalForm);
            editor.putBoolean("industrial_tax", industrialTax);
            editor.putBoolean("turnover_tax", turnoverTax);
            editor.putBoolean("disbursal", disbursal);
            editor.putString("capitalownership", capitalOwnership);
            editor.putString("est_income", estIncome);
            editor.commit();
        }
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(TAG, "updateTextView()", e);
    }
}
like image 699
THE-E Avatar asked Apr 19 '18 12:04

THE-E


2 Answers

The first time you've saved capitalownership you probably didn't save it as a String, so when you try to retrieve it, it will retrieve an Integer but you try to cast to String when you do getString and it will get the exception.

String tmp = prefs.getString("capitalownership", "0");

try like this:

int tmp = prefs.getInt("capitalownership", 0);

Besides, you've already set your edit text to input only numbers, so you won't get a String here.

Edit:

Shared Preferences are stored as a Map<String, Object>. As you can see the value of the map is a general Object, if you saved as an Integer you'll need to retrieve as an integer. Ths is quite dynamic, so if you saved one time as an integer and the next time as a String (to the same key) you need to keep track of the type you've saved so you can retrieve it.

If you've saved once as Integer and later save again (in the same key) as a String, when you retrieve it you'll need to use getString(). If you're not sure what's in there you can use the getAll() method to retrieve the entire preferences as a Map<String, Object>, then you can use get("capitalownership") in this map and finally check with instanceof to see what type it is. But this is too cumbersome, you need only to estabilish that you'll save that key(capitalownership) with a certain type and make sure you do that always.

So this is what's happening:

1)You try to retrieve the value associated with that key and Android gives you an Object,

2) Android then tries to cast to the value associated with the method (a String in your case). As the value is actually an Integer that's where the class cast problem comes from.

like image 111
Levi Moreira Avatar answered Nov 15 '22 00:11

Levi Moreira


https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String,%20java.lang.String) :

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

So I'm guessing you have a "capitalownership" preference that has been stored as an Integer

like image 28
stephendnicholas Avatar answered Nov 14 '22 23:11

stephendnicholas