2012-09-05 68 views
1

我在我的應用程序中使用Datepicker。我想要做的是獲取已設置在文本字段中的日期,並在Datepicker控件上顯示該日期。但我得到NumberFormatException當我使用Integer.parseInt拋出NumberFormatException?

Integer.parseInt(splittedDate[2]) //i.e the year column. 

當我看到,而調試splittedDate containf三個值都很好。但在解析年份列的最後一個索引時拋出異常。我無法理解爲什麼會這樣。請幫我解決這個問題。以下是Datepicker的CreateDialog方法的實現。

@Override 
protected Dialog onCreateDialog(int id) { 
    if (id == DATE_DIALOG_ID) { 
     if (birthDate.getText().toString().equalsIgnoreCase("")) 
      return new DatePickerDialog(this, mDateSetListener, mYear, 
        mMonth, mDay); 
     else { 
      String[] splittedDate = birthDate.getText().toString().split("-"); 

      try{ 

       Log.i("Month String", splittedDate[0]); 
       mMonth = Integer.parseInt(splittedDate[0]); 
       Log.i("Day String", splittedDate[1]); 
       mDay = Integer.parseInt(splittedDate[1]); 
       Log.i("Year String", splittedDate[0]); 
       mYear = Integer.parseInt(splittedDate[2]); 

      } 
      catch(Exception e) 
      { 
       Log.e("Number Format Exception Message: ",e.getMessage()); 
      } 

      return new DatePickerDialog(this, mDateSetListener, mYear, 
        mMonth, mDay); 

     } 

    return null; 
} 

這裏是logcat的信息:

09-05 16:21:54.722: E/AndroidRuntime(28596): FATAL EXCEPTION: main 
09-05 16:21:54.722: E/AndroidRuntime(28596): java.lang.NumberFormatException: unable to parse '1970 ' as integer 
09-05 16:21:54.722: E/AndroidRuntime(28596): at java.lang.Integer.parse(Integer.java:383) 
09-05 16:21:54.722: E/AndroidRuntime(28596): at java.lang.Integer.parseInt(Integer.java:372) 
09-05 16:21:54.722: E/AndroidRuntime(28596): at java.lang.Integer.parseInt(Integer.java:332) 
09-05 16:21:54.722: E/AndroidRuntime(28596): at com.test.project.activity.DetailActivity.onCreateDialog(DetailActivity.java:332) 
+0

你能發佈導致異常的字符串嗎? – MByD

+0

可否請上傳stacktrace – harshit

+0

它基本上是splittedDate數組中的第三個元素......它的值是1970 –

回答

0

後的代碼,你在birthDate字段中插入值。檢查應該不存在任何blank spaces。應該只有數字。從例外情況看,'1970 '似乎包含一個空格。仔細檢查birthDate字段..

+0

確實如此。我將.trim()添加到我的值,它工作得很好。 –

+0

:)快樂編碼.. –

1

試試這個

Integer.parseInt(splittedDate[2].toString()) 
+0

它已經是一個字符串,這就是爲什麼它打印在日誌 –

+1

它沒有任何作用,因爲它已經是一個字符串。 –

+0

你得到錯誤,因爲「1970」包含在其中的空白空間,將其刪除,然後解析它 – Fawad

相關問題