1

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]);
    }
2
  • What if quizDescs[0] is null? Commented Nov 18, 2014 at 9:16
  • you check if your text is empty but you should also check if your list quizDescsexists. Commented Nov 18, 2014 at 9:16

4 Answers 4

2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

If either quizDescs or quizDescs[0] are null, you'll get a NullPointerException.

Obviously, if isEmpty() returns false, it means that isEmpty() was executed, so quizDescs[0] is not null when the condition returns true, and that's why it works.

Either make sure that both quizDescs and quizDescs[0] is never null, or change the condition to :

if (quizDescs != null && quizDescs[0] != null && !quizDescs[0].isEmpty()) {
    ....
} else {
    ....
}

Comments

0

You have an error because quizDescs is Null so when you try to get quizDescs[0] in the condition, you try to get the first item of null object.

Comments

0

The only possible ways the if-line can cause a NullPointerException, is when quizDescs itself is null or the first element quizDescs[0] is null. Try to extract quizDescs into a local variable for debugging purposes and inspect its content.

You can either initialize your array with empty strings or add a check for null - or better review your logic how null is a possible condition. Usually null values should be avoided (see Bloch, Effective Java 2nd Edition, item 43 for a similar case).

1 Comment

No. The second possible way is that quizDescs itself is null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.