1
votes

I am new to using shared preferences and on my first try im getting errors that don't make sense to me. I assign a value like this:

int saveScore = sp.getInt("SAVE_SPOT",0); //This is intentional to get the 
                                          //default value of 0 to go to case 0


switch(saveScore){
     case 0:
           SharedPreferences.Editor edit1 = sp.edit();
           edit1.putInt("SCORE_1", score);
           edit1.putInt("SAVE_SPOT", 1);
           edit1.commit();
           break;
    case 1:
           int previous_score = sp.getInt("SCORE_1",0); // error happens here
           if(sp.getInt("SCORE_1",0)>score){

            SharedPreferences.Editor edit2 = sp.edit();
            edit2.putInt("SCORE_2", score);
            edit2.putInt("SAVE_SPOT", 2);
            edit2.commit();

             }
            else{

             SharedPreferences.Editor edit3 = sp.edit();
             edit3.putInt("SCORE_2", previous_score);
             edit3.putInt("SCORE_1", score);
             edit3.putInt("SAVE_SPOT", 1);
             edit3.commit();
                        }

        break;

Every time i run the program i get the error "string cannot be cast to integer". I am almost 99% sure the variable score is an int and not a string but I am not sure why i am getting this error.

3
The exception is thrown at putInt correct? Where are you assigning score?eski
the exception is on the getInt line. score is a variable that is updated as a button is pressed and then outside of the on click listener is where the shared preferences code isez4nick
Have a look at my solution. I hope it helpsDan Bray

3 Answers

1
votes

You can check to make 100% it is an int by using this function:

public static boolean IsInteger(String s)
{
   if (s == null || s.length() == 0) return false;
   for(int i = 0; i < s.length(); i++)
   {
       if (Character.digit(s.charAt(i), 10) < 0)
           return false;
   }
   return true;
}

If putInt won't work, you could use Integer.parseInt( instead.

1
votes

I solved my issue, un installing the app is necessary every time in testing because thats the only way to clear the stored data

0
votes

It seems that with putInt() it won't let you put anything but an int, so that is odd. Are you really telling the full story here?

My guess is that you have ANOTHER key that has the name SCORE_1 that was actually stored as a string, and when you're grabbing out the int, it's picking up the String instead. That's the only way. According to the API:

Throws ClassCastException if there is a preference with this name that is not an int.

So I think SCORE_1 is already in there, and was stored as a string. For the hell of it, try to get out SCORE_1 using getString() instead.

See here: http://developer.android.com/reference/android/content/SharedPreferences.html#getInt%28java.lang.String,%20int%29