问题:在我的设备上打开游戏时,我收到错误,LogCat说:
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.SharedPreferencesImpl.getLong(SharedPreferencesImpl.java:247)
at com.lochdownstudios.projectmoney.GamePage.getDouble(GamePage.java:300)
at com.lochdownstudios.projectmoney.GamePage.onCreate(GamePage.java:101)
(行号显然现在不适用于此)我意识到问题是某些东西仍然是整数,但我很困惑,无法找到导致此问题的原因。
代码:
public class GamePage extends Activity {
protected Double iMoney = 0.0;
protected TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_page);
money = getDouble(myPreferences, "money", iMoney);
tv = (TextView) findViewById(R.id.txtMoney);
tv.setText("Money: " + money);
}
double getDouble(final SharedPreferences prefs, final String key, final double defaultValue) {
return Double.longBitsToDouble(prefs.getLong(key, Double.doubleToLongBits(defaultValue)));
}
}
注意:所有导入都包含在实际文件中。
答案 0 :(得分:2)
查看异常堆栈中报告的类/方法的源代码。像grepcode这样的网站可以提供帮助。第247行,SharedPreferencesImpl显然对于首选项名称“money”返回的数据类型(可能是Integer)进行了强制转换。
public long More ...getLong(String key, long defValue) {
245 synchronized (this) {
246 awaitLoadedLocked();
247 Long v = (Long)mMap.get(key);
248 return v != null ? v : defValue;
249 }
250 }