-4

this is my code to check if the value of column is not null

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

but I get this:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference

What is the proper way to check if value return by res is empty

Brownman Revival
  • 3,620
  • 9
  • 31
  • 69
  • looks like res is null in if-statement. please provide some more code – XtremeBaumer Nov 14 '16 at 10:23
  • Try this if(res.getString(res.getColumnIndex("answerquestionid")) != null && !res.getString(res.getColumnIndex("answerquestionid")).trim().equals("")) – Raghavendra Nov 14 '16 at 10:23
  • @Raghavendra this one is return error `!res.getString(res.getColumnIndex("answerquestionid")).trim(‌​).equals("")` but first one is ok can you provide it as answer so i can close the OP? – Brownman Revival Nov 14 '16 at 10:28

4 Answers4

1

Try this,

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

//your stuff

}
Raghavendra
  • 2,305
  • 25
  • 30
  • i am getting error if i include this `&& !res.getString(res.getColumnIndex("answerquestionid")).trim(‌​).equals("")` any idea? – Brownman Revival Nov 14 '16 at 10:32
  • Looks like res.getString(res.getColumnIndex("answerquestionid")) is null so u need to do a null check before accessing trim() method – Raghavendra Nov 14 '16 at 10:34
0

Try this:

if(res.getString(res.getColumnIndex("answerquestionid"))!=null){
DLIK
  • 50
  • 7
0

You are checking the value of something which may be null, which will throw a Null object reference. to fix this you must check if the String is 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 you can do it in one if statement but I find the above more readable.

if (res != null) {
    if( res.getString(res.getColumnIndex("answerquestionid")) != null &&
        res.getString(!res.getColumnIndex("answerquestionid")).trim().equals("")) {
        //Safe to use String
    }
}
Hughzi
  • 2,470
  • 1
  • 20
  • 30
0

You have two ways for it:

First is checking if res exists (best approach)

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

Because if it returns 0 it means it doesn't exists.

Second way is checking if string is null

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

Your problem was that you were not checking if the String result was null

Hope this helps

Pier Giorgio Misley
  • 5,305
  • 4
  • 27
  • 66