You get a NullPointerException
when you try to call a method using a variable that is null
. Simple example:
String s = null;
int len = s.length(); // NullPointerException because s is null
So you should check if the variable is null
before calling any method on it, for example:
int len;
if (s == null) {
len = 0;
}
else {
len = s.length(); // safe, s is never null when you get here
}
Note that a NullPointerException
is usually easy to solve. Carefully look at the stack trace of the exception, it tells you exactly in which line of your code the exception happens. Check what could be null
in that line of code, and check if you're calling a method on something that might be null
. Add a check (or prevent that the relevant thing can ever be null
in another way).