【发布时间】:2018-09-29 23:39:49
【问题描述】:
我正在开发适用于 Android 的应用程序,但无法弄清楚我正在犯的错误或错误。我搜索错误超过 4 小时。
我在使用 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)
但根据我的理解,我并没有在该行中进行演员表。第 36 行是方法 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"));
}
我对 XML 文件的偏好如下:
<EditTextPreference
android:defaultValue="0"
android:dialogTitle="@string/capitalownership"
android:inputType="number"
android:key="capitalownership"
android:title="@string/capitalownership" />
我需要我将发布完整的代码和完整的错误列表。
我对 Android 比较陌生。
解决方案
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);
}
}
【问题讨论】:
-
String tmp = prefs.getInt("capitalownership", "0")+""
-
String tmp = prefs.getString("capitalownership", "0")-->这必须是整数。
-
显示 SharedPreferencesImpl.java 类中第 235 行的代码
-
将“资本所有权”更改为您声明的字符串
标签: java android exception casting sharedpreferences