通过res检查返回值为null

时间:2016-11-14 10:21:35

标签: java android

这是我的代码,用于检查列的值是否为空

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

但我明白了:

  

java.lang.NullPointerException:尝试调用虚方法' java.lang.String java.lang.String.trim()'在空对象引用上

检查res返回的值是否为空的正确方法是什么

4 个答案:

答案 0 :(得分:1)

试试这个,

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

//your stuff

}

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

您正在检查可能为null的值的值,这将抛出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
    }
}

答案 3 :(得分:0)

你有两种方法:

首先检查res是否存在(最佳方法)

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

因为如果它返回0,则意味着它不存在。

第二种方法是检查字符串是否为空

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

您的问题是您没有检查String结果是否为null

希望这有帮助

相关问题