I have a list that takes a list from my server. this list will hold whatever the server finds at the database ex.
List<OBJ> lstObj = new Arraylist<OBJ>;
Service.getOBJ(new AsyncCallback<List<OBJ>>(){
#Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
#Override
public void onSuccess(List<OBJ> result) {
//line to check if result is null
}
});
I have tried
if(result==null){
}
and also tried
if(result.isempty(){
}
but it didnt work. the list will be null if the server doesnt find any record from the database. all i need to do is check if the list is empty.
Checking if the list is empty and checking if result is null are very different things.
if (result == null)
will see if the value of result is a null reference, i.e. it doesn't refer to any list.
if (result.isEmpty())
will see if the value of result is a reference to an empty list... the list exists, it just doesn't have any elements.
And of course, in cases where you don't know if result could be null or empty, just use:
if (result == null || result.isEmpty())
Check number of elements in resulting List:
if (0==result.size()) {
// Your code
}
You will do like this:
if (test != null && !test.isEmpty()) { }
This will check for both null and empty, meaning if it is not null and not empty do your processing.
You're obviously new at this programming thing if you didn't already validate your server, so I'm trying to aim a guess at what might be going on with your server. Depending on what your "" objects are, you could have valid objects that represent data that is meaningless in different ways. For example, you may have String objects with various kinds of white space.
This happens a lot on servers that provide answers using PHP and JSP, where pages are assembled using various include mechanisms and there is white space between them.
The below should do for your code. If you want a negation logic just modify accordingly.
As also suggested by someone CollectionUtils provide just utility methods which removes such null check LOC.
result == null || result.isEmpty()
Hope this helps!
Related
Sometimes developers checks if Strings are null values, if yes, sets those Strings as empty value:
if (text == null) {
text = "";
}
What I want to do is to write opposite if statement:
if (text.isEmpty()) {
text = null;
}
But...first of all - I have to check (as usually) if this String is null to avoid NullPointerException, so right now it looks like this (very ugly but KISS):
if (!text == null) {
if (text.isEmpty()) {
text = null;
}
}
My class has several String fields and for all of them I have to prepare this solution.
Any basic ideas for more efficient code? Is it a good way to strech it to lambda expressions and iterate throught all String fields in this class?
Another alternative using Guava's emptyToNull:
text = Strings.emptyToNull(text);
I don't know the context in which you thought to mention streams relating to your question, but if you are open to the Apache StringUtils library, then one option would be to use the StringUtils#isEmpty() method:
if (StringUtils.isEmpty(text)) {
text = null;
}
In your example, if text is null then text.equals(null) will cause a NPE. You will want something like this:
if (text != null && text.isEmpty()) {
text = null;
}
If you want whitespace considered empty as well, you will want to call trim() before calling isEmpty():
if (text != null && text.trim().isEmpty()) {
text = null;
}
Since you want to reuse this code, it makes sense to make this a utility method that you can call from any class:
public static String setNullOnEmpty(final String text) {
return text != null && text.trim().isEmpty() ? null : text;
}
Don't use equals() to check if a string is null, but:
if (text == null)
So
if (text != null && text.isEmpty()) {
text = null;
}
This 1 line condition won't throw NPE if text is null because of short circuit evaluation.
You can do the same thing by using a one if statement like below,
if (text != null && text.isEmpty()) {
text = null;
}
I don't have a better answer to your exact problem than what has already been posted. However, I would strongly question why you would want to conflate empty strings and nulls into nulls. Nulls are generally a bad idea, a "billion-dollar mistake", to quote Tony Hoare, who himself invented null references. This blog post has some good arguments!
Have you considered going the opposite direction, converting any null strings to empty strings? That way you only have to deal with strings for most of your code and can stop worrying about null pointer exceptions.
Better yet, take a look at the Optional type, which represents an object that may or may not be present. This came about in Java 8 as a better way to represent absence than nulls. Here's a blog post that explains it.
We have a method in org.apache.commons.lang.StringUtils.trimToNull(s); and with this we can get the empty string value to null value
String text = StringUtils.trimToNull(emptyStringValue);
I have a Spring JPA search criteria like below. Where area is an Integer.
cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())
The question is, when the user does not specify an upper bound or lower bound in the search, the value is null and this results in NPE. One thing comes to my mind is to make an if check for null values and set the value to Integer.MAX_VAL if it is null as a work around.This way I can avoid NPE, but it is also going to create a lot of if else checks. So I want to know if there is a better way.
Two cleaner solutions come to my mind:
using Optionals e.g. `Optional.ofNullable(searchConstraint.getAreaMax()).orElse(Integer.MAX_VALUE)
areaMin and areaMax should have sensible default values which are overwritten only if user provided some data ; the data itself should be validated
if getAreaMin and getAreaMax are NULL you can avoid/ignore to add this criteria .
if getAreaMin is NULL and getAreaMax is NOT NULL you can use le() instead of between , and the same for getAreaMax with gt() method;
'if' code is ok.
something like this :
if(isNotNull(searchConstraint.getAreaMin()) && isNotNull(searchConstraint.getAreaMax())) {
cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())
}else{
if(isNotNull(searchConstraint.getAreaMin()){
cb.gt(root.get(Property_.area), searchConstraint.getAreaMin());
}else{
cb.le(root.get(Property_.area), searchConstraint.getAreaMax());
}
}
Or you can create a util method like (but the prev variant is better dut to performance issue):
private Integer getValueOrDefault(Integer value , Integer defaultValue){
return value==null ? defaultValue : value;
}
execute :
cb.between(root.get(Property_.area), getValueOrDefault(searchConstraint.getAreaMin(), Integer.MIN_VALUE), getValueOrDefault(searchConstraint.getAreaMax(), Integer.MAX_VALUE))
If both values can be null I'd suggest splitting the between query into two predicates and then combining them. This way you can also handle the case when both of them are null:
List<Predicate> predicates = new ArrayList<>();
if (searchConstraint.getAreaMin() != null)
predicates.add(cb.gt(root.get(Property_.area), searchConstraint.getAreaMin()))
if (searchConstraint.getAreaMax() != null)
predicates.add(cb.lt(root.get(Property_.area), searchConstraint.getAreaMax()))
if (predicates.size() > 0)
cb.and(predicates.toArray(new Predicate[predicates.size()]))
I'm trying to catch an exception. I thought that checking whether the String is empty would help, but it doesn't seem to work. The value in the actual column for the object in my class is "(undefined)". It seems to be that by default. How can I explicitly check to see if it is undefined?
notifications.getString(ParseConstants.KEY_FEED_TYPE).isEmpty()
Heads up. The following doesn't work either:
notifications.getString(ParseConstants.KEY_FEED_TYPE).equals("(undefined)");
it's checking using Android default function like
if (!TextUtils.isEmpty(notifications.get(ParseConstants.KEY_FEED_TYPE))) {
// its not null value success
} else {
// here getting to null value Fail
}
I did the following. Instead of looking for a String (in which case the field entry would be truly empty, and not (undefined)), I checked to see if the object was null after dropping the String from getString.
if (notifications.get(ParseConstants.KEY_FEED_TYPE) != null) {
// Do something.
} else {
// Do something else.
}
I was doing this String name = doc.select("h1#name").first().text(); and I received a NullPointerException on a page where the 'h1#name' element did not exist. I'm parsing the DOM, grabbing hundreds of elements. It seems that I need to test each element before I assign, so I changed it to this:
String name = null;
if( doc.select("h1#name").first() != null && doc.select("h1#name").first().text() != null ))
name = doc.select("h1#name").first.text();
Is there a better way to do it? I'm just learning Java, and my background is in Perl, where I'd do something like this:
my $name = $doc->select("h1#name")->text if $doc->select("h1#name");
It's not a big deal, since my code does work for me. I was just wondering if there was a cleaner way to do this in Java.
You will not come arround checking all objects you go throuth to access the value you want.
To translate your perl syntax into java I would use the ternary operator:
name = doc.select("h1#name").first() != null ?
doc.select("h1#name").first().text() : null
There is no need to check doc.select("h1#name).first().text() != null too unless you have a non null value in name and you don't want to override it with null.
I would suggest a utility method, something like this:
Document mDocument;
(...)
String getElementTextOrNull (String cssQuery) {
Element e = mDocument.select(cssQuery).first();
if (e == null) {
return null;
} else {
return e.text();
}
}
Then, you can eliminate a lot of boilerplate and repetition, so your code simply becomes:
String name = getElementTextOrNull("h1#name");
You can also do other things in that method, like checking if the text is empty or if it is valid.
Of course, this may be impractical if you only get the text of a specific element once, but this is what I would suggest otherwise. Personally, I also think this is neater and more concise than the ternary operator solution proposed in the other answer.
I have the following code within a for loop to see if a string equals a search string:
if(Data.coord[i].equals(Data.search))
I've tested the code with exact values i.e if 1=1 and the rest of the code works fine. It just doesn't like the string comparison. The consol gives out this error:
Exception in thread "main" java.lang.NullPointerException
at highercoursework.Search.main(Search.java:16)
at highercoursework.Main.main(Main.java:16)
Thanks
You should compare the constant to your parameter since it can be null.
For example if Data.search is a constant which you are searching for you should do this:
if(Data.search.equals(Data.coord[i]))
In this case you won't end up trying to call methods on a null reference and you won't need unnecessary null checks either.
You have an unpopulated element in your array i.e.
Data.coord[i]
is null. Note that Data.search could be null, but the equals() method will handle this. You just need to perform the lement check first.
String[] coord = new String[100];
This will mean you can assign something to coord[0] but until you do that coord[0] is null. Hence the null pointer exception.
You can try.
String data= Data.coord[i];
if(data != null && data.equals(Data.search))
you can avoid your problem in two ways:
In the case coord[i] should not be null
if (Data.coord[i] != null) {
if(Data.coord[i].equals(Data.search)) {
}
} else {
logger.error("Unexpected Behavior: coord[i] should not be null");
}
Note: You can replace the logger message by a more appropriated code that fit to your requirement.
In the case your your coord[i] can be null
comparing in this way won't throw an exception if Data.coord[i] is null. (Assuming Data.search is a constant and can't bu null) So the rules for this case is: use in priority a String object constant to call the method equals.
if (Data.search.equals(Data.coord[i])) {}
Read this to understand What is a Null Pointer Exception?
if coord[] is initialized properly, value of Data.coord[i] may be null. You can check
if(Data.coord[i] != null && Data.coord[i].equals(Data.search)) {}
Try this:
if(DATA != null && Data.coord[i].equals(Data.search))