-4

I'm having problems with a NullPointerException.

I was doing the debugging and the element is not null, I have the problem in the first IF and I can not see what the problem is. I thought that happened when the state of the element was null, but I tried to fix it and it did not work

// Update: The problem is when I Check the status

for (Items item : master.getItems()) {
try {
    if (item.getCompany_status().equals("active") || item.getCompany_status().equals("open")) {

if (item.getAddress_snippet() == null) {
    cont2++;
    Company c = new Company(item.getTitle(), "");                            
    arrayCompany.add(c);
}else {
    cont2++;
    Company c = new Company(item.getTitle(), item.getAddress_snippet());                                 
    arrayCompany.add(c);
}
} catch (Exception e) {
     e.printStackTrace();
}
}
}
R.Sanchez
  • 33
  • 7
  • 1
    `item.getAddress_snippet().equals(null)` is almost certainly wrong. Use `==` to compare to `null` – JonK Apr 16 '19 at 09:34
  • if `getAddress_snippet()` in `item.getAddress_snippet().equals(null)` returns null, the call .equals() won't work because null isn't an object with methods. You'll need to write `item.getAddress_snippet() == null` – Tschallacka Apr 16 '19 at 09:34
  • This is a NPE, so you missed the actual variable being null. With a [mcve] or at least the stacktrace, we could confirm what you missed. Please [edit] your question with the information. And FYI, from [`Object.equals`](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-) you can read "_For any non-null reference value x, x.equals(null) should return false._" – AxelH Apr 16 '19 at 09:44

2 Answers2

1

I strongly recommend to make the equals the other way:

Instead of:

item.getCompany_status().equals("active")

Do:

"active".equals(item.getCompany_status())

This way, at runtime, if the status is null, it won't crash as it first checks the string.

It is more likely to have "value".equals(null) than null.equals("value") as you can't call .equals() from a null object.

Carlos López Marí
  • 1,432
  • 3
  • 18
  • 45
0

This is Strongly type so it tem.getCompany_status() is null , it gives null pointer exception,

item.getCompany_status().equals("active") || 
item.getCompany_status().equals("open")

So, use

"active".equals(item.getCompany_status()) || 
"open".equals(item.getCompany_status())
Bishal Jaiswal
  • 1,684
  • 13
  • 15