简体   繁体   中英

Getting java.lang.String cannot be cast to java.lang.Integer when retrieving value from SharedPreferences

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.

I have tried converting the value to a string and then using Integer.ParseInt to retrieve the value, but I still get an error.

This is where my value should be stored:

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...
}
}

And I try to retrieve it like this:

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

On the getSavedValues method I get the error

java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

What I don't understand is the fact that I save the value as int and try to retrieve them the same way.

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.

After cleaning the app data and and Invalidate and clear cache in Android Studio the issue disappeared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM