2013-06-29 52 views
1

我是新來的使用共享偏好,並在我第一次嘗試即時獲得對我沒有意義的錯誤。我給這樣一個值:字符串不能被轉換爲整數

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; 

每當我運行程序時,我得到的錯誤「字符串不能被轉換爲整數」。我幾乎99%肯定變量分數是一個整數,而不是一個字符串,但我不知道爲什麼我得到這個錯誤。

+0

唯一的例外是在putInt正確拋出的唯一途徑?你在哪裏分配分數? – eski

+0

異常在getInt行上。 score是一個變量,當按下按鈕時被更新,然後在點擊監聽器之外是共享首選項代碼的位置 – ez4nick

+0

查看我的解決方案。我希望它幫助 –

回答

0

它似乎與putInt()它不會讓你把任何東西,但一個int,所以這很奇怪。你真的在這裏講完整的故事嗎?

我的猜測是你有另外一個名字爲SCORE_1的鍵,它實際上是作爲一個字符串存儲的,而當你抓取出整數時,它會選擇String。這是唯一的方法。根據API:

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

所以我覺得SCORE_1已經在那裏,並存儲爲一個字符串。對於它的地獄,嘗試使用getString()代替SCORE_1

在這裏看到:http://developer.android.com/reference/android/content/SharedPreferences.html#getInt%28java.lang.String,%20int%29

+0

,即使當我試過這個:String score1 = sp.getString(「SCORE_1」,「0」);它說整數不能被轉換爲字符串 – ez4nick

+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

我解決我的問題,未安裝該應用程序是必要的測試每次都因爲那清除存儲的數據

+0

是的,問題是你有一個相同的名稱存儲爲一個字符串的變量,你永遠不會清除它。文檔中提到'getInt()'「返回首選項值(如果存在)或defValue。如果存在不是int的此名稱的首選項,則拋出ClassCastException。 – LuckyMe