2016-11-14 100 views
-4

這是我的代碼檢查,如果列的值不爲空檢查返回值的資源是空

if(!res.getString(res.getColumnIndex("answerquestionid")).trim().equals("")){

,但我得到這個:

顯示java.lang.NullPointerException:嘗試在空對象引用上調用虛擬方法'java.lang.String java.lang.String.trim()'

什麼是正確的方法來檢查是否val通過RES UE回報爲空

+0

看起來像res在if語句中爲null。請提供更多代碼 – XtremeBaumer

+0

試試這個if(res.getString(res.getColumnIndex(「answerquestionid」))!= null &&!res.getString(res.getColumnIndex(「answerquestionid」))。trim()。equals(「 )) – Raghavendra

+0

@Raghavendra這一個是返回錯誤'!res.getString(res.getColumnIndex(「answerquestionid」))。trim().equals(「」)'但第一個是好的,你可以提供它作爲答案我可以關閉OP? –

回答

1

試試這個,

if(res != null){ 
    if(res.getString(res.getColumnIndex("answerquestionid")) != null && !res.getString(res.getColumnIndex("answerquestionid")).trim(‌​).equals("")) 

//your stuff 

} 
+0

如果包含此&&!res.getString(res.getColumnIndex(「answerquestionid」))。 ).equals(「」)'有什麼想法? –

+0

看起來像res.getString(res.getColumnIndex(「answerquestionid」))爲null,所以你需要在訪問trim()方法之前做一個空檢查 – Raghavendra

0

試試這個:

if(res.getString(res.getColumnIndex("answerquestionid"))!=null){ 
0

要檢查的東西,可以爲null,這將拋出一個空對象引用的值。要解決此問題,您必須檢查String是否爲null

if (res != null) { 
    String str = res.getString(res.getColumnIndex("answerquestionid")); 
    if(str != null) { 
     // Perform action 
    } else { 
     // String is null so recover (use placeholder, try again etc) 
    } 
} 

alternativley你可以在一個if語句中做到這一點,但我發現上面更具可讀性。

if (res != null) { 
    if(res.getString(res.getColumnIndex("answerquestionid")) != null && 
     res.getString(!res.getColumnIndex("answerquestionid")).trim().equals("")) { 
     //Safe to use String 
    } 
} 
+0

如果res.getString(res.getColumnIndex(「answerquestionid」))本身爲null,該怎麼辦? – Raghavendra

+0

我已經刪除了對Trim的調用,但它沒有在Op的代碼中拋出異常。我覺得你的downvote在這裏放錯了位置。 – Hughzi

+0

如果'res'本身爲空,該怎麼辦? –

0

你有這兩種方式:

首先是檢查是否存在資源(最好的方法)

if(res.getIdentifier(myStringName) != 0){ 
    //do stuff 
} 

因爲如果它返回0,則意味着它不存在。

第二種方法是檢查,如果字符串爲null

String myRes = res.getString(myStringName); 
if(myRes != null && !myRes.trim().equals("")){ 
    //do stuff 
} 

你的問題是,你沒有檢查是否String結果是null

希望這有助於