NullPointerExceprion at recursive method - java

I have this recursive method:
public Hund getMor(int id) {
Hund barn = getHund(id);
int idMor = barn.getId_mor();
Hund mor = getHund(idMor);
return mor;
}
public String getMorTre(int id) {
if (id == 0) {
return null;
}
if (!existHund(id)) {
return "Hunden du søkte etter finnes ikke";
} else {
if (id == 0) {
return null;
} else {
Hund mor = getMor(id);
MinRamme.jta.append(mor.toString() + "\n");
int morId = mor.getId();
return getMorTre(morId);
}
}
}
I have tried to remove the nullpointer by returning null if the id is 0 but this does not work. Does anyone have a solution?
NPE:
Exception in thread "AWT-EventQueue -0" java.lang.nullpointerexception
at Arkiv.getMorTre(Arkiv.java:209)
at Arkiv.getMorTre(Arkiv.java:211)
at Arkiv.getMorTre(Arkiv.java:211)
at MinRamme$4.actionPerformed(MinRamme.java:89) <37 internal calls>

Where does the NullPointerException occur? That would help... That being said:
Inside your else clause, your
if (id==0) {
is useless, since you're testing that at the beginning and the id isn't changed.
I think you need to check if
getMother(id)
returns null, that is probably where you're getting the NullPointer... but you could confirm that now, couldn't you?

It is likely (but difficult to confirm until you let us know what line is throwing the NPE) that the line that generates the NPE is
MyFrame.jta.append(mother.toString() + "\n");
because mother is null. You could change your code into this:
Dog mother = getMother(id);
if (mother == null) {
//do something
}

There really isn't enough information here. What line are you getting the null pointer on?
if, as I suspect, it's here:
MyFrame.jta.append(mother.toString() + "\n");
Then you need to determine, through debugging, that it's definitely mother that is null. If you have done that, then you can be absolutely positive that your getMother(id); returns null, for the id that you are passing in.
If I were you I would create a unit test for the getMother(id) method and pass in the id that is causing the failure.
If you don't know what id value is causing the problem, then at the very least stick in some System.out.print() statement to find out what is going on. Although, you'd be better using some logging framework, such as log4j.
Hope this helps.

Its because your exception is at mother.toString() method..
try this
try
{
MyFrame.jta.append(mother.toString() + "\n");
}catch(NullPointerException ignore){}

Related

Handle null pointer exception

I have the following code:
String a= null
Element element = ...
if(element == null) {
System.out.println("...");
}
a = element.getText();
I got a null pointer exception on this code.
I thought that it would be better to use an if else statement in order to avoid this error.
String a= null
Element element = ...
if(element == null) {
System.out.println("...");
} else {
a = element.getText();
}
Is it a good solution to use the above code to solve the problem or it would be better to manage it another way?
I got a null pointer exception on this code
Yes, because you don't not execute element.getText() if element == null.
Element element = ...
if(element == null) { // This check is irrelevant to...
System.out.println("...");
}
a = element.getText(); // ...whether this statement is executed.
Is it a good solution
It's a solution, because the else isn't executed when element == null.
You might consider inverting the condition, so the "happy" case (the one you want to execute when things are working normally) comes first. But this is not an important difference, functionally.
if(element != null) {
a = element.getText();
} else {
System.out.println("...");
}
You approach is ok since it works and you dont get the NPE anymore.
You could invert the if condition and simplify things like:
String a= null
Element element = ...
if(element != null) {
a = element.getText();
}
This way you do your things in a protected code block and you don't need else part unless you really wanted to print "..."
Yes it is a solution for the reasons already mentioned by the other answers. I want to provide another solution:
String a;
try {
Element element = ...;
a = element.getText();
} catch (NullPointerException e) {
System.out.println("...");
a = null; // Or some other value that can be tested but cannot produce a NPE
}
This would have the same error handling as your if statement, but it has the advantage, that ´element´ cannot be referenced later and produce a NPE somewhere else. This is of course only useful if the String cannot produce a NPE either way and if the Element could actually used later (in other words if the method doesn't end directly afterwards).

"Duplicate local variable" and "void is an invalid type for the variable" errors

I keep getting those two errors and cannot seem to understand why. These errors suddenly appeared in other methods as well, further down the same class. I have tried to find double declarations but could not find any. Also, I have paid attention to to write a method within another method. Help will be much appreciated! :)
public void connectStudentToCourse(long studentID, String courseID)
{
if (studentID >= 0 && courseID != null)
{
boolean flag = false;
Course tempCourse = new Course(courseID);
tempCourse = sData.getCourses().get( sData.getCourses().indexOf(courseID) );
Student stu = new Student(studentID);
stu = sData.getStudents().get( sData.getStudents().indexOf(studentID) );
if (tempCourse != null && stu != null)
{
if (tempCourse.getPreCourses() != null)
for (Course c : tempCourse.getPreCourses())
{
for (Course passed : stu.getCompletedCourses())
{
if (passed.equals(c))
flag = true;
}
if (flag == false)
{
MyFileLogWriter.writeToLogFile("Failed to connect Student "+studentID+" to course "+courseID+"\n", false);
return;
}
else flag = false;
}
if (tempCourse.addStudent(stu))
{
if (stu.addCourse(tempCourse))
{
MyFileLogWriter.writeToLogFile("Student "+stu.getId()+" connected to course "+tempCourse.getCourseID()+" successfully\n", false);
return;
}
else //RollBack
tempCourse.removeStudent(stu);
}
}
}
MyFileLogWriter.writeToLogFile("Failed to connect Student "+studentID+" to course "+courseID+"\n", false);
}
I think you have to add opening bracket at 2nd if statement and close it, may it solve your problem...
Only when I cut all the problematic methods from the class, I noticed a missing "}" in the method above them. Eclipse did not show this missing brace, only until I removed all the rest of the code, so I could not tell where was it missing until the removal. I added the missing brace and re-pasted the rest of the problematic methods back into the class, and all errors have vanished! Solution was much more simple than I expected it to be. #PM77-1, #Jon Skeet and #Andreas - you are all LEGENDS!! Thank you so much!! :)

null value in comparison seems to be not null

Normally I make a comparison in every activity(Android) but I have a problem and I couldn't find the solution. I tried everything I could but result is still the same.
In if statement null value seems to be not null.
What am I doing wrong?
Here is the code :
System.out.println(item.getSub()); // output is null
if (item.getSub()!=null) {
r.putExtra("engsub", item.getSub()); // Normally it shouldn't, but it goes in here
startActivityForResult(r, position);
}
else {
//Do something
}
And I tried this :
String def = item.getSub()+"";
System.out.println(def); // output is not null
if (!def.equals("")) {
r.putExtra("engsub", item.getSub()); // Normally it shouldn't, but it goes in here
startActivityForResult(r, position);
}
else {
//Do something
}
Added :
JSONArray jsonResponse = new JSONArray(result);
asd = new String[5][jsonResponse.length()];
rowItems = new ArrayList<RowItem2>();
for (int i = 0; i < jsonResponse.length(); i++) {
JSONObject js = jsonResponse.getJSONObject(i);
// ....codes
asd[4][i] = js.getString("engsub");;
item = new RowItem2(asd[0][i], asd[1][i], asd[2[i],
asd[3][i],asd[4][i]);
rowItems.add(item);
}
RowItem2 class
private String engsub;
public RowItem2(String title, String desc,String desc2,String desc3,String engsub) {
this.engsub = engsub;
//......
}
//.......
public String getSub() {
return engsub;
}
public void setSub(String engsub) {
this.engsub = engsub;
}
I think JSON string result contains the word "NULL" in it.
Look at the docs about JSONObject on Android Developer site.
Here is the line that solves your problem:
When the requested type is a String, other non-null values will be
coerced using valueOf(Object). Although null cannot be coerced, the
sentinel value NULL is coerced to the string "null".
Below some ideas when trying to track down an issue like this:
Confirm your assumptions
You sound confused, so set your mind at ease. There is nothing wrong with Java / Android. Confirm this with a change that will work correctly every time.
This change challenges your assumption: you assume that item.getSub() is returning null.
String nullString = null;
System.out.println(nullString);
if (nullString != null) {
r.putExtra("engsub", item.getSub()); // Normally it shouldn't, but it goes in here
startActivityForResult(r, position);
}
else {
//Do something
}
This will NOT pass the if test, unless there is something wrong with your IDE.
Confirm your IDE is working
You may still think you are getting null. In some cases it could look like this.
Sometimes Eclipse will not put the correct code onto your emulator / device. There could be an issue with the build.
So do a project Clean. Then build again and test.
This will confirm that you are running the correct code.
Confirm what you are seeing
Sometimes when output looks like a "" string, it can be " " or " ".
Try logging your output surrounded by [ and ].
System.out.println("[" + item.getSub() + "]");
Look deeper into the code
This is why I asked to see the item.getSub() code, and the extra you have shown.
If the above tests don't help, look to see how that value is set / returned.
Looking into JSONObject.getString() javadoc, it shows that it cannot return a null value:
In your case, log out the JSON string, and log out the values in RowItem2 constructor.
That should show you the "NULL" I refer to at the top of this answer.
You could try:
if (item.getSub() instanceof String) {
r.putExtra("engsub", item.getSub()); // Normally it shouldn't, but it goes in here
startActivityForResult(r, position);
}
else {
//Do something
}
This way you're sure that the item.getSub() is a string.
Try this,
if(!"".equals(your string)
{
// do something
}

Avoid null checks?

I wonder if it would be possible to 'avoid' null checks in Java, take an example from this code:
#Override
public List<AccountBean> search(AccountConstraint... c) {
if (c.length == 0) {
throw new IllegalArgumentException("dao.AccountDAO.search: c.length == 0");
}
try {
List<AccountBean> beans = new ArrayList<>();
for (AccountConstraint ac : c) {
Builder builder = new QueryBuilder.Builder("SELECT * FROM accounts");
if (ac.getAccountId() != null) {
builder.clause("accountId >= " + ac.getAccountId().getMin() + " AND accountId <= " + ac.getAccountId().getMax());
}
if (ac.getUsername() != null) {
builder.clause("username = \"" + ac.getUsername() + "\"");
}
if (ac.getPassword() != null) {
builder.clause("password = \"" + ac.getPassword() + "\"");
}
if (ac.getEmail() != null) {
builder.clause("email = \"" + ac.getEmail() + "\"");
}
PreparedStatement ps = connection.prepareStatement(builder.build().getQuery());
ResultSet rs = ps.executeQuery();
while (rs.next()) {
beans.add(new AccountBean(rs));
}
}
return beans;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
It has to check 4 times for the != null because else the code would fail.
Is it possible to turn the if (object != null) statements into one-liners that only execute if there is no NullPointerException? When there is an exception, the line should just be ignored.
I am not talking about a general language feature here, I am talking about a feature that would only be turned in when you explicitely decide to do so.
For example: NullCheck(builder.clause("username = \"" + ac.getUsername() + "\"")); would be a snippet of the suggested code.
Is something like that possible in Java?
Also if it is not possible, might it be possible in Java 8 to use methods (voids) directly in methods?
So then code like this could actually work?
public static NullCheck(Void void) {
try {
void.execute();
}
catch (NullPointerException e) {
//ignore
}
}
I know I could put the method inside it's own class that extends an interface that has method execute() and then pass that class around, but that would defeat the purpose of getting rid of the null checks or anything that would be even more complicated.
Regards.
WARNING: The way I used PreparedStatement here is prone to SQL Injection. Do not reuse this code.
You can avoid these checks by assuming that these methods do not return null values.
How can you assume this? By having the specification for the AccountConstraint say so. The code in AccountConstraint is then responsible for ensuring the values are not null, rather than your search method being responsible for handling null values. You might have to change the design of AccountConstraint to do this.
And what happens if your assumption is wrong? That is, if AccountConstraint is buggy. An exception will be thrown, which you were not expecting. But that is what can happen when you have a bug: an unexpected exception is thrown. Debugging the code will be easy, because the stacktrace will show you which method of AccountConstraint is returning an invalid null value.
Yes and No.
There are two approaches to tackle the null problem:
Special Operators like the Safe Navigation Operator in Groovy. If x.y throws a NullPointerException x?.yreturns just null. Since Java does not allow creation of new operators, you can't do this in Java. Operators like this where considered for JDK8 but where dropped. If you want have something like this, switch to Groovy or one of the many other languages having this feature.
Special Class many languages have a special interface for representing a value that might be null. In Scala it is called Option. Option has two implementations: None + Some. None replaces null. Whenever you want to do something with the value, you don't use it directly, but you call map on the Option with a function as an argument. If it is actually a None, nothing happens, you just get back None. If it is a Some, the function gets executed on the value and you get an Option with the result. That way you can work with Options all the time, without worrying about nulls.
Actually it is in now way special, so you can create such a class yourself with Java. The problem is only, that Java doesn't have functions, so you have to use anonymous classes. This makes the whole thing really cumbersome and only a theoretical option.
JDK8 has a Option class. As far as I know it is missing the map method which makes the whole thing a bad joke in my opinion. But since the most important tool (anonymous functions) are there will be a proper Option implementation provided by one of the usual suspects (Google, Apache ...)
As it stands, you could probably write a method like
public void clauseIfNotNull(Builder builder, String format, Object o) {
if (o != null) {
builder.clause(String.format(format, o));
}
}
and then that'd look like clauseIfNotNull(builder, "username = \"%s\"", ac.getUsername());
Other than that, there's not much you can do with Java 7.
Make a minimal adaptor object on the Builder
class NotNullClauseAdapter
{
private final Builder builder;
public NotNullClauseAdapter(Builder builder) {
this.builder = builder;
}
public void clause(String format, Object o) {
if (o != null) {
builder.clause(String.format(format, o));
}
}
}
Use this in your code:
for (AccountConstraint ac : c) {
Builder builder = new QueryBuilder.Builder("SELECT * FROM accounts");
NotNullClauseAdapter adapter = new NotNullClauseAdapter(builder);
if (ac.getAccountId() != null) {
builder.clause("accountId >= " + ac.getAccountId().getMin() + " AND accountId <= " + ac.getAccountId().getMax());
}
adapter.clause("username = \"%s\"", ac.getUserName());
adapter.clause("password = \"%s\"", ac.getPassword));
adapter.clause("email = \"%s\"", ac.getEmail());
PreparedStatement ps = connection.prepareStatement(builder.build().getQuery());
ResultSet rs = ps.executeQuery();
while (rs.next()) {
beans.add(new AccountBean(rs));
}
}
You can expand by adding further clause-methods to the adapter to handle specific objects like ranges in order to convert things like the accountId as well, e.g.
public void clauseMinMax(String format, Range r) {
if (r != null) {
builder.clause(String.format(format, r.getMin(), r.getMax()));
}
}
The accountId row then becomes (if getAccountId() returns a Range object):
adapter.clauseMinMax("accountId >= %d AND accountId <= %d", ac.getAccountId());
Use JSR305 and use the appropriate #Nonnull annotations and you don't have to do null checks, the annotations do them for you.
The use of #Nonnull and #CheckReturnValue annotations from JSR305 help to express the needs for null and return value checks. It is a good practice that the developer describes the expected behavior of the implementation for the later use and the static code analysis.

Weird nullpointer exception

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.

Categories