2016-10-03 93 views
-7

我從壓延得到的日期和使用上SimpleDateFormat的空指針異常解析

SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yyyy"); 
    Date date = null; 
    try { 
     date = sdf1.parse(datevalue); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 

    if(date != null) { 
     Date d = new Date(date.getTime()); 
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
     return sdf.format(d); 
    } 

    return ""; 

轉換其格式,但我在某些設備上的越來越崩潰對一些設備來說,是工作的罰款。
我不知道爲什麼它僅在某些設備上發生。

我在面料報告得到這個:

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference  
     at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1044) 
     at java.text.DateFormat.parse(DateFormat.java:577) 
     at com.app.appUtilities.Utilities.convertDateFormat(Utilities.java:34) 

請幫助我。

+5

''datevalue'在某些情況下顯然是'null'。 – Bathsheba

+0

您在第二行上分配了null到date的引用。 –

+0

它被初始化在第三行,因爲你可以看到如果你有任何公平的答案,然後評論 –

回答

0
String dateStr = "04/05/2010"; 

    SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); 

    try { 
     dateObj = curFormater.parse(dateStr); 
    } catch (ParseException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy"); 

    String newDateStr = postFormater.format(dateObj); 
    Toast.makeText(getApplicationContext(), newDateStr, 1).show(); 
+0

SimpleDateFormat sdf1 =新的SimpleDateFormat(「MM/dd/yyyy」); \t \t Date date = null; \t \t嘗試{ \t \t \t date = sdf1.parse(datevalue); \t \t} catch(ParseException e){ \t \t \t e。的printStackTrace(); \t \t} \t \t如果(日期!= NULL){ \t \t \t日期d =新的日期(date.getTime()); \t \t \t SimpleDateFormat sdf = new SimpleDateFormat(「yyyy-MM-dd'T'HH:mm:ss.SSSZ」); \t \t \t return sdf.format(d); \t \t} \t \t return「」; –