从SharedPreferences检索值时,无法将java.lang.String强制转换为java.lang.Integer [英] Getting java.lang.String cannot be cast to java.lang.Integer when retrieving value from SharedPreferences
问题描述
我正在尝试使用SharedPreferences存储一些值并在应用程序打开时检索它们,但是我在检索某些int值时遇到问题。
I am trying to use SharedPreferences to store some values and retrieve them when the app opens, but I have issues with retrieving some int values.
我尝试了转换将该值转换为字符串,然后使用Integer.ParseInt检索该值,但仍然出现错误。
I have tried converting the value to a string and then using Integer.ParseInt to retrieve the value, but I still get an error.
这是应该存储我的值的位置:
void putP1Index(int index) {
SharedPreferences.Editor mEditor = mPrefs.edit();
mEditor.putInt(keyP1Index, index);
mEditor.apply();
}
void putP2Index(int index) {
SharedPreferences.Editor mEditor = mPrefs.edit();
mEditor.putInt(keyP2Index, index);
mEditor.apply();
}
它们是从另一个类中保存的:
They are saved from a different class:
private MainGame mainGame;
private SavedValues savedValues;
ScoreSetter(MainGame mainGame) {
this.mainGame = mainGame;
savedValues = new SavedValues(mainGame);
}
void setScore(who) {
switch (who) {
case 1:
++indexP1;
savedValues.putP1Index(indexP1);
//Some code...
case 2:
++indexP2;
savedValues.putP2Index(indexP2);
//Some code...
}
}
我尝试这样检索它:
int getP1Index() {
return mPrefs.getInt(keyP1Index, 0);
}
int getP2Index() {
return mPrefs.getInt(keyP2Index, 0);
}
通过从不同的类别进行呼叫:
by calling them from a different class:
void getSavedValues() {
indexP1 = savedValues.getP1Index();
indexP2 = savedValues.getP2Index();
}
在getSavedValues方法上,我得到了错误
On the getSavedValues method I get the error
java.lang.RuntimeException:无法启动活动ComponentInfo {...}:java.lang.ClassCastException:java.lang.String无法转换为java.lang。整数
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
我不明白的是我将值保存为int并尝试以相同方式检索它们的事实。
What I don't understand is the fact that I save the value as int and try to retrieve them the same way.
此外,我也有类似的方法,但是使用 booleans 即可,而且效果很好。
Also, I have a similar method but with booleans and it works just fine.
推荐答案
我设法解决了该问题。代码没有什么错,但是它的值是在该应用的先前版本中编写的。
I managed to fix the issue. There was nothing wrong with the code, but with a value that was written in a previous version of the app.
在清理应用程序数据并在Android Studio中无效并清除缓存后,问题消失了。
After cleaning the app data and and Invalidate and clear cache in Android Studio the issue disappeared.
这篇关于从SharedPreferences检索值时,无法将java.lang.String强制转换为java.lang.Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!