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);
}
}