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.
keyP1IndexorkeyP2Indexis a string written in a previous version of the app?