!array[0].isEmpty() returning NullPointer?

Total Post:47

Points:331
 1169  View(s)
Ratings:
Rate this:

Here's my code:

if (!quizDescs[0].isEmpty()) {
    mDescText.setText(quizDescs[0]);
} else {
    mDescText.setVisibility(View.INVISIBLE);
}

So, when this code runs, and the if condition returns true, everything is fine and dandy, however, if it returns false, it says there's a NullPointerException, and points me to the line of code containing the if statement.

Am I checking the condition right? Why is it returning a NullPointer?!

ANSWER:

    if (quizDescs[0] == null) {
       mDescText.setVisibility(View.INVISIBLE);
    } else {
       mDescText.setText(quizDescs[0]);
    }

  1. Post:28

    Points:196
    Re: !array[0].isEmpty() returning NullPointer?

    if quizDesc[0] is String, you can do

    if(!StringUtility.isEmptyOrNull(quizDesc[0])){
     mDescText.setText(quizDescs[0]);
    }else {
        mDescText.setVisibility(View.INVISIBLE);
    }

    By the way, Null and being empty is not same

    Consider

    String s; //Initialize to null
    String a =""; //A blank string
    Its always a good practise to use
    try{
       //Your code here..
    }catch(Exception e){
        e.printStacktrace();
    }

      Modified On Apr-06-2018 06:58:01 AM

Answer