Weird nullpointer exception - java

I have this method in my superclass, which extends activity:
protected boolean isStopAvailable(BusStop stop) {
if (stop == null) {
stop = new BusStop();
} else if (stop.getName().length() > 0) {
return true;
} else {
return false;
}
return false;
}
I call it in my subclass isStopAvailable(object); How is it even possible to get a null pointer exception while using a method from the object after I've initiated the object?

stop.getName() returns null
else if (stop.getName() != null && stop.getName().length() > 0)
should solve it

If getName() returns null, you will get a NPE. You are trying to do a length function on a null object, hence this exception. You should add another else if check:
...
else if (stop.getName() == null) {
// do something
}
Hope this helps.

I would bet that the name field in stop is null. Your first check is to see if the object is null, not the fields inside of it. Thus, if stop.getName() returns null, you get an NPE when attempting to invoke the length

I suggest that the NPE is thrown in this line: else if (stop.getName().length() > 0)
Thats possible because you've checked if the object BusStop is null but you didn't checked if stop.getName() could be null.
Do something like that:
else if (stop.getName() == null) {
// set stop.setName()
}
Hope this helped, Have Fun!

stop.getName() is returning null ,that is why you are getting NPE.

Related

I have an 'if' statement for checking null pointer exception but that line itself is giving a null pointer excpetion

Code
if (dataSnapshot.child("Email").getValue().toString()==null) {
Email.setText("Email not found");
} else {
Email.setText(dataSnapshot.child("Email").getValue().toString());
}
if (dataSnapshot.child("Quote").getValue().toString()!=null) {
Email.setText(dataSnapshot.child("Quote").getValue().toString());
} else {
Email.setText("Quote not found");
}
The line of the if statement is itself showing an error. How do I solve this problem?
You're checking if the toString() value is null. Only that value.
You're not checking any of the values that precedes it.
dataSnapshot could be null.
dataSnapshot.child("Email") could be null.
dataSnapshot.child("Email").getValue() could be null.
Take each value, save it to a variable, and do a null check on ALL those values.
This is the only way to do it in Java.
Here is how you can rewrite it:
if(dataSnapshot != null && dataSnapshot.hasChild("Email") && dataSnapshot.child("Email").getValue() != null ){
//Your code...
}
You have to check for all possibilities.
if (dataSnapshot.child("Email").getValue().toString()==null) {
}
install a breakpoint before if and debug it. I think either dataSnapshot is null or dataSnapshot.child("Email") is resulting null which is causing err.

null pointer exception in writing file in java

I am facing an exception while writing to the file. i am giving the code below.
private static void readCsvFromFileAmazon(List<String> filelist)
throws BiffException, IOException,NullPointerException {
FileWriter fw = new FileWriter("total_number_of_products_amazon.txt", true);
String numberOfProducts = getProductNumber(url);
System.out.println(category);
System.out.println("##############" + numberOfProducts);
// call function to get the number of products. \
if (!numberOfProducts.equals(null) || !numberOfProducts.equals(" "))
{
fw.write(numberOfProducts);
}
else
{
System.out.println("cant write null product");
}
fw.close();
}
the value getting in number of products is null then exception happening
Exception in thread "main"
##############null
java.lang.NullPointerException
exception happening in this line
if(!numberOfProducts.equals(null)||!numberOfProducts.equals(" "))
You must check numberOfProducts content in different way:
if(null != numberOfProducts ||!"".equals(numberOfProducts))
instead of if(!numberOfProducts.equals(null)||!numberOfProducts.equals(" "))
because if numberOfProducts is null, then invoke a method equals on null object throws a nullPointerException.
Hope this helps,
in your if statement numberOfProducts.equals(null)
you are comparing a string to a null string. this doesnt have any effect since you are comparing a null object.
remember that String is an object and you need to check object if they are null in this kind of way numberOfProducts == null or numberOfProducts != null
You cannot check if null.equals(null) - it throws an exception, NullPointerException, for tying to access the equals() method of null. First, make sure numberOfProducts is not null itself, using the == operator:
if (numberOfProducts == null) {
//do something
} else {
...
}
Also note that the line
if(!numberOfProducts.equals(null)||!numberOfProducts.equals(" "))
Makes no sense logically. Assuming null.equals(null) would work (IT DOES NOT), The second (right) operand - !numberOfProducts.equals(" "), will be evaluated only if numberOfProducts == null, so whenever the right operand is evaluated - it will always yield false.
This means your condition could be shortened to simply:
if (numberOfProducts != null)
As you posted for:
System.out.println("##############"+numberOfProducts);
Output is:
##############null
This means numberOfProducts is null hence if you attempt to call any non-static method on it like this:
numberOfProducts.equals(null)
will throw a NullPointerException. If you want to check if it's null, do it like this
if (numberOfProducts != null && !numberOfProducts.equals(" ")) {
fw.write(numberOfProducts);
}
I think this will work
if(numberOfProducts!=null && !numberOfProducts.rquals(" ")){
//doSomething
}else{
//doSomethingElse
}

Is there any chance of this code printing null?

String readwidget(int a, int b){
WidgetChild readwidget = Widgets.get(a,b);
if(readwidget.getText() != null){
Task.sleep(10);
System.out.println(readwidget.getText());
return readwidget.getText();
}
Task.sleep(10);
return GOT_NULL;
}
while(readFirstWidget.equals(GOT_NULL) && t5.isRunning()) {
readFirstWidget = readwidget(1184, 13);
Task.sleep(50,80);
}
This piece of code is crashing with nullpointerexception once in while(1 out of 50 time) and it prints null at that point of time which it should not. Can anyone please help me to find out the causes? Thanks in advance.
You mention in a comment that Widgets.get(a,b) can return null. Given that, you need to guard against that possibility by checking the return value from the method for null prior to actually calling any instance methods on it. You aren't doing that, and so you are crashing in that case.
All you need to do is add the null check and your code should be fine:
WidgetChild readwidget = Widgets.get(a,b);
if(readwidget != null && readwidget.getText() != null) {

using method that take variable number of parameters

I am trying to make a method that build new object of the class (PhoneBook) using different constructors according to the number of parameters ,, but it gives an error
( Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 )
public static PhoneBook createObjects(String fName,String lName,String num,String...optional)
{
n++;
if (optional[0]==null)
ArrayOfObjects[n]=new PhoneBook(fName,lName,num);
else if (optional[1]==null)
ArrayOfObjects[n]=new PhoneBook(fName,lName,num,optional[0]);
return ArrayOfObjects[n];
}
Instead of checking whether optional[0] == null, you should examine optional.length to determine if the optional parameter is present.
The same goes for optional[1].
Rather than checking optional[0] and optional[1] here, you should check to optional.length. Also, keep in mind that optional itself may well be null, so something like:
if(optional != null) {
if(optional.length > 0) {
// I now know that optional has at least one element in it, and optional[0] should be valid, though I don't know that it is non-null.
if(optional.length > 1) {
// I now know that optional[1] is valid, though I do not know it is non-null.
}
}
}
if you NEED non-null:
if(optional.length > 0 && optional[0] != null)
The second part, optional[0] != null will only be called if the first evaluates to true.

How to catch the exception caused by an absence of an object in Java?

I have a very simple method:
public int getScore() {
return game.gameWindow.userBestScore;
}
The problem is that it can happens that game object or gameWindow do not exist. I do not want to get the Null Pointer Exception. How can catch it in a correct way? Can I do it in this way:
public int getScore() {
try{
return game.gameWindow.userBestScore;
} catch(NullPointerException e){
return -1;
}
}
Do not catch a NullPointerException.
A NullPointerException is a sign that your code is not adhering to some contract. If it is possible that game can be null, then you need to make an explicit test:
if(game != null) {
...
}
else {
...
}
If game should not be null, then you can ensure the correctness of your code by using assert.
assert game != null;
...
What is more worrying is that game seems to be a private member of your class. In this case game should probably not be null (although there are cases where this can happen). Are you initializing it properly in your constructor? I'd say that the first thing you should is to make sure that game is being initialized properly. Otherwise your code will end up being littered with un-necessary null-checks. For example, what if gameWindow in the Game class wasn't initialized properly? You would need to have another null-check for that:
if(game !== null && game.gameWindow != null) {
...
}
else {
...
}
So you should first make sure that your object's private members are being initialized properly. If they are, and it turns out that there is a valid use-case for game being null, then you would need an explicit null-check. It's always better to test for null than catching a NullPointerException. Other than the fact that exceptions should not be used to control the flow of your business logic, what if a valid NullPointerException (due to a programming error) was generated somewhere up the chain? Now your catch will catch it and you won't know about it; this can lead to some really nasty and hard-to-find bugs.
You can do that. You can also check to see if game and gameWindow are null before trying to access userBestScore.
if(game != null && game.gameWindow != null)
return game.gameWindow.userBestScore
Check whether the variables are null as shown below:
public int getScore() {
if(game == null || game.gameWindow == null){
return -1;
}
return game.gameWindow.userBestScore;
}
public int getScore() {
return ((game == null || game.gameWindow == null) ? -1 : game.gameWindow.userBestScore);
}
You can do that. OR you can check for null before you dereference those objects and take appropriate action without throwing an exception. That'll be more efficient.
The real question you should be asking is: Why on earth would an object have null references for private data members? You aren't constructing your objects properly. An object should be properly initialized and 100% ready to go after you create it. Otherwise, you end up having to be unnecessarily defensive in your code.
Avoid exception throwing as much as possible. Handling the known issues is the better way than throwing exceptions.
In some where you have to do a null check. Probably before calling the getScore() method, because that doesn't make a sense of calling that method if the game or gameWindow is null.
if (game != null && gameWindow != null)
{
int score = getScore();
}
OR
public int getScore()
{
if (game != null && gameWindow != null)
{
return game.gameWindow.userBestScore;
}
else
{
return -1;
}
}
Don't do duplicate null checkings.

Categories