string不能转换为整数

时间:2013-06-29 00:13:10

标签: android string casting int

我是新手使用共享首选项,并在我第一次尝试时获取对我没有意义的错误。我指定了这样的值:

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;

每次运行程序时都会收到错误“string不能转换为整数”。我几乎99%肯定变量得分是一个int而不是一个字符串,但我不知道为什么我得到这个错误。

3 个答案:

答案 0 :(得分:1)

您可以使用此功能检查100%是否为int:

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

如果putInt不起作用,您可以改为使用Integer.parseInt(

答案 1 :(得分:1)

我解决了我的问题,每次测试都需要安装应用程序,因为这是清除存储数据的唯一方法

答案 2 :(得分:0)

似乎用putInt()它不会让你放一个除int之外的东西,所以这很奇怪。你真的在这里讲完整的故事吗?

我的猜测是你有一个名为SCORE_1的另一个密钥,它实际上存储为一个字符串,当你抓住int时,它会取而代之的是字符串。这是唯一的方法。根据API:

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

所以我认为SCORE_1已经存在,并存储为字符串。最糟糕的是,尝试使用SCORE_1取代getString()

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

相关问题