Why am I getting a NullPointerException with my array? - java

I cant figure out why I am getting a NullPointerException. What am I missing here ?
public class CustomJourneyUserInformation {
public IJourneyDetails journeyDetails;
public IUserDetails userDetails;
public ISubscribeJourney subscribedToJourneys;
}
IJourneyDetails, IUserDetails, ISubscribeJourney are all interfaces
In a different activity, I am calling
private CustomJourneyUserInformation[] allJourneyDetails;
allJourneyDetails = new CustomJourneyUserInformation[subscribedToJourneys.length];
if (providerDetails[i] != null)
>>> allJourneyDetails[i].journeyDetails = providerDetails[i];
if (userDetails[i] != null)
allJourneyDetails[i].userDetails = userDetails[i];
if (subscribedToJourneys[i] != null)
allJourneyDetails[i].subscribedToJourneys = subscribedToJourneys[i];
I am getting a null pointer exception in line marked by >>>>
I am sure allJourneyDetails[i] is null here.

It looks like allJourneyDetails[i] is null, since the array is still filled with null after initialization.
Did you expect creating the array to fill the array with non-null values? That's not how it works in Java.

allJourneyDetails = new CustomJourneyUserInformation[subscribedToJourneys.length];
should be
allJourneyDetails = new CustomJourneyUserInformation[providerDetails.length];
too; but #LouisWasserman is right

Related

Having null in a value of a ListResourceBundle implementation

In a ListResourceBundle implementation I define an array with some keys containing null values.
It compiles fine the loading process of the bundle containing a null value. However when I call getObject on a key with a non-null value (like in the following example "Pollution" which has value "high"), it gives me a NullPointerException.
Do you have an idea why it happens in that way?
ResourceBundle labels = ResourceBundle.getBundle("bundlething", new Locale("it"));
labels.getObject("Pollution");// here NullPointerException, However Pollution has a \n
value, other keys of the same array do not.
UPDATE:
This is the stacktrace I receive:
Exception in thread "main" java.lang.NullPointerException at
java.util.ListResourceBundle.loadLookup(ListResourceBundle.java:196)
at
java.util.ListResourceBundle.handleGetObject(ListResourceBundle.java:124)
at java.util.ResourceBundle.getObject(ResourceBundle.java:387) at
ResourceBundleThing.main(ResourceBundleThing.java:38)
and this is the bundle I load by passing new Locale("it") as target Locale:
import java.util.ListResourceBundle;
public class bundlething_it extends ListResourceBundle {
private Object [][] contents ={{"Inhabitants",null},{"Pollution",new Double(3.4034)},{"Lollerball",new Integer(132)}};
public Object[][] getContents()
{
return contents;
}
}
There is null corresponding to "Inhabitans" however I am referring only to "Pollution" which has a non-null value. Still I get a NullPointerException; If I remove that null from "Inhabitants" it works.. so it's there the problem, I know. However I would like to know why since I am not using that particular key-value pair.
Does it load all the values as soon as getObject it's called?
Thanks in advance.
The stack trace precisely indicates where the error comes from:
Object[][] contents = getContents();
HashMap<String,Object> temp = new HashMap<>(contents.length);
for (int i = 0; i < contents.length; ++i) {
// key must be non-null String, value must be non-null
String key = (String) contents[i][0];
Object value = contents[i][1];
if (key == null || value == null) {
throw new NullPointerException(); // <-- HERE
}
temp.put(key, value);
}
So, you have your answer: although I haven't seen it mentioned in the documentation, ListResourceBundle doesn't allow null values.

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) {

Some fields in a Java array are null, handling of these

I have the following code snippet.
Explanation:
I have the array called result.
This array consists of different String attributes like "city", "countryName" and "IATA".
With a for loop, I try to access and retrieve all the aforementioned fields.
My problem now is: While "city" and "countryName" always have a value, "IATA" sometimes does not have a value and thus returning me "null", which leads to the nullPointerException as soon as I access an empty "IATA".
I tried this:
if(entry.getIATA().equals(null)) {
} else {
startIATA[count] = entry.getIATA();
}
But, this if condition is not working as I try to access a field which is null.
Has anyone an idea how I can solve this?
Here is the relevant code snippet:
private String[] startIATA = new String[200]; //That is more than long enough
...
for (int count = 0; count < result.getAirports().length(); count++) {
AirportsEntry entry = result.getAirports().get(count);
// Block for StartAirport
HorizontalPanel hp = new HorizontalPanel();
hp.setSpacing(5);
hp.add(new Label(entry.getCity()));
hp.add(new Label(entry.getCountryName()));
hp.add(new Label(entry.getIATA()));
GWT.log("IATA: " + entry.getIATA());
if(entry.getIATA().equals(null)) {
} else {
startIATA[count] = entry.getIATA();
}
startAirportVP.add(hp);
}
Thank you very much for your time and your help!
Perform a simple null check prior to accessing the property of the object.
if(entry != null && entry.getIATA() != null){
startIATA[count] = entry.getIATA();
}
You cannot use equals method to check for null. Use ==:
if (entry.getIATA () == null)
use this:
if (entry.getIATA() != null)

How to detect if a long type is actually NULL?

We have a nullable (type long) column (named referral) in our MySQL database. We use hibernate for ORM.
I am trying to get the value of the column for a given member. Some are null, and if its not, its an id that points to another member whose is the referrer.
The problem is in the java code I am trying to detect if that member's column is null, if not, do something.
String referrerAffiliateId = Long.toString(member.getReferral());
if (referrerAffiliateId != null){
//do something
}
member.getReferral() returns the value (type long) of the referral column. Some of those columns are null and some are not.
The above code compiles fine, but I get a nullPointerException when I call the method on a user whose referral column is null.
How do I properly do a detection on this?
Thanks in advance!
Full Answer:
Thanks to #Marcelo for the best correct answer.
Here is the code in its final state:
Long referrerAffiliateId = member.getReferral();
if (referrerAffiliateId != null) {
//...
}
Assuming member.getReferral() returns a Long, use:
if (member.getReferral() != null)
In Hibernate, if you want to be able to detect nullability in a property, you must not use primitive types, because they will always have a default value 0 for longs.
The exception probably comes from Long.toString(), try checking the value before converting to a string:
Long ref = member.getReferral();
if (ref == null) {
// Do something...
} else {
String referrerAffiliateId = Long.toString(ref);
// ...
}
Change
String referrerAffiliateId = Long.toString(member.getReferral());
if (referrerAffiliateId != null){
//do something
}
To:
if (member.getReferral() != null){
String referrerAffiliateId = Long.toString(member.getReferral());
//do something
}
It's likely that you're getting the NullPointerException when you call Long.toString() with a null parameter.
use Below code:
Long ref = member.getReferral();
String referrerAffiliateId = null;
if(ref != null){
referrerAffiliateId = Long.toString(ref);
}

Null pointer exception double

Can somebody explain me why I am getting a NullPointerException here:
String s = request.getParameter("tbExample");
_tbExample = new Double (Double.valueOf(s).doubleValue());
s may be null. According to javadoc, if s is null, valueOf will throw a null pointer exception.
Try checking s for null before continuing.
Probably the tbExample parameter does not exist in your request.
Therefore null is being returned to indicate that fact, and is being assigned to s. This is then passed to Double.valueOf, which is invalid input.
Try something like this:
String s = request.getParameter("tbExample");
if(s == null)
{
// Handle the error.
// You could log something, throw exception, exit early, etc.
// Do whatever is appropriate for your application.
}
else
{
_tbExample = new Double (Double.valueOf(s).doubleValue());
}
I can see why you are confused here. You are taking a String, parsing it into a Double, turning it into a double and back into a Double again. A much simpler solution is to do
_tbExample = s == null ? null : Double.valueOf(s);
This handles the situation where s is null and turns a String into a Double
Here is a simple test program for you.
Double _tbExample;
String s = null;
_tbExample = s == null ? null : Double.valueOf(s);
System.out.println("_tbExample="+_tbExample);
prints
_tbExample=null

Categories