0

Why does this cause the error?

if (extras != null) {
    if (extras.getString("ActionBar") != null) {
        if (extras.getString("ActionBar").equals("NO")) {
            if (bar != null) bar.setDisplayHomeAsUpEnabled(false);
        }
    }
}

I check to make sure that it is not null first.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
spen123
  • 3,464
  • 11
  • 39
  • 52
  • Have you confirmed that `extras` itself is not `null`? – CommonsWare Nov 21 '15 at 22:06
  • Do you know what a NullPointerException is? – Tunaki Nov 21 '15 at 22:07
  • @CommonsWare yes, that was a mistake when posting code – spen123 Nov 21 '15 at 22:12
  • Is it an error? It looks like a warning from your IDE. – osundblad Nov 21 '15 at 23:16
  • @osundblad its a IDE Warning but I would still like to remove it – spen123 Nov 21 '15 at 23:25
  • @spenf10 which line are you getting the warning on? I could maybe understand the `if (extras.getString("ActionBar").equals("NO")` since it might be to complex for the IDE to catch? If so you could remove the prior null check and just do `if ("NO".equals(extras.getString("ActionBar"))` which would be doing the null check implicitly. – osundblad Nov 21 '15 at 23:41
  • @spenf Old question but was it maybe that `extras` was not final? If not it might change to null after the null check. – osundblad Nov 18 '16 at 21:09

2 Answers2

2

You are calling extras.getString("ActionBar") twice. Once you check the returned value against null (but never use it) and once you use it without checking it against null. Now, maybe the contract of that function says that if it is called with identical arguments, it will always return identical values, but this need not be the case and your IDE probably doesn't know.

You should store the return value in a (preferably final) variable, then the warning should go away.

if (extras != null) {
    final String actbar = extras.getString("ActionBar");
    if (actbar != null) {
        if (actbar.equals("NO")) {
            // ...
        }
    }
}

This might also be a performance advantage because you don't need to do getString's work twice.

Anyway, if your code is full of such massive aggregations of if (o != null) { … } checks, this might be an indication of code smell.

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
1

You get the warning because you may not receive any bundle (from the sender activity e.g) since you don't initialize it in the current context (or activity). So in this case, if you don't check if extras is null (and extras was in deed equal to null), this line:

if (extras.getString("ActionBar") != null)

would throw a NullPointerException. Therefore, you must check if extras is null first to avoid any potential crash.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67