I'm looking to populate an object with some values from a complex xml object. To get to the right value i have to get through a big chain of elements and i have to check them all to not be null. So my code will look like this X 9 times. I don't want to stop the populate process just because one element is missing, I want to 'skip' the null pointer somehow and get to the next propriety. My only idea is to put every line in a try/catch block. Got any better ideas? Thanks
objModel.setProviderHeadquarterName(obj.getObject("YYY") != null && obj.getObject("YYY").getArray("gob") != null && obj.getObject("YYY").getArray("gob").size() > 0 && obj.getObject("YYY").getArray("gob") != null ? obj.getObject("YYY").getArray("gob").getObject(0).getString("gobValue") : "");
objModel.setProviderHeadquarterName(obj.getObject("XXX") != null && obj.getObject("XXX").getArray("tem") != null && obj.getObject("XXX").getArray("tem").size() > 0 && obj.getObject("XXX").getArray("tem") != null ? obj.getObject("XXX").getArray("tem").getObject(0).getString("temValue") : "");
objModel.setProviderHeadquarterName(obj.getObject("ZZZ") != null && obj.getObject("ZZZ").getArray("has") != null && obj.getObject("ZZZ").getArray("has").size() > 0 && obj.getObject("ZZZ").getArray("has") != null ? obj.getObject("ZZZ").getArray("has").getObject(0).getString("hasValue") : "");
How can
You can wrap this in an Optional and deal with the nulls implicitly:
Optional.of(obj).map(o -> o.getObject("YYY")).map(o -> o.getArray("gob")) /* [snip] */
.orElse(""); //etc
To answer your question literally, you could extract that in a separate method and catch the potential exceptions. But that's not best practice:
private static Object getValueOrNull(Supplier<Object> s) {
try {
return s.get();
} catch (Exception e) { //narrow down the exception if possible
return null;
}
}
Which you can call like this (the value may be null):
Object value = getValueOrNull(() -> obj.getObject("YYY").getArray("gob").getObject(0).getString("gobValue"));
Related
I'm trying to avoid a NullPointerException in some code that tries to compare with a string from a HashMap.
The HashMap is well defined but there may or may not be a corresponding entry in the HashMap so I believe this may be where my NPE and the associated Android Studio warning may be coming from.
My code is:
if (region_ids !=null && source_region != null && selected_id != null) {
if (source_region.equals("it") && region_ids.containsKey("it") && !selected_id.equals(region_ids.get("it").toString())) {
// Do stuff for mismatched region
}
}
Where region_ids is the HashMap.
Am I doing enough to prevent NullPointerExceptions?
If so, why is Android Studio still giving me the warning in the IDE?
(Note that the Android-Studio tag is included intentionally because of the last part of this question which is AS specific.)
Update
Based on Code-Apprentice's comment and Nosyara's answer I now have the following two variations on the if statement but still get the NPE warning on the toString() method:
if ( region_ids_string != null && spin_region_id != null && source_region != null && selected_id != null && assoc_ids != null) {
if ( region_ids_string.size() > spin_region_id.getSelectedItemPosition()) {
if (source_region.equals("com_mx") && assoc_ids.get("com_mx") != null && assoc_ids.containsKey("com_mx") && !selected_id.equals(assoc_ids.get("com_mx").toString())) {
return true;
} else if ("com_au".equals(source_region) && assoc_ids.containsKey("com_au") && assoc_ids.get("com_au") != null && !assoc_ids.get("com_au").toString().equals(selected_id)) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
So I believe I am now checking for null, "", and whether the Key exists in the HashMap but AS still believes it is possible for the statements to generate an NPE...
If you reverse condition with constant to the left, you'll automatically check it for NULLs. Like so:
if ("it".equals(source_region) &&
region_ids.containsKey("it") &&
!(region_ids.get("it").toString().equals(selected_id))) {
// Do stuff for mismatched region
}
Please find my below code that am checking for null using ternary operator before am setting the value to my bean class attributes.
doc.setCatalog_description(sourceAsMap != null && sourceAsMap.get("catalog_description") != null ? sourceAsMap.get("catalog_description").toString() : null);
Is there anyother way to simplify this code like below., Am just exploring by using org.apache.commons.lang3.ObjectUtils; methods. But am not sure that it is correct or not.
doc.setCatalog_description(ObjectUtils.identityToString(sourceAsMap.get("catalog_description")));
I think you are looking for the method ObjectUtils.toString(Object).
if (sourceAsMap != null) {
final String description = ObjectUtils.toString(sourceAsMap.get("catalog_description"));
doc.setCatalog_description(description);
}
If you are using jdk7 or higher, you can replace the method by java.util.Objects.toString(Object).
if (sourceAsMap != null) {
final String description = Objects.toString(sourceAsMap.get("catalog_description"));
doc.setCatalog_description(description);
}
I don't know if sourceAsMap can be null, but if you are setting several parameters, you should check if it is null just once.
In the interest of readability and clarity I would suggest just extracting this bit of functionality into its own method:
String getDescOrNull(Map<String, Object> sourceAsMap) {
final String key = "catalog_description";
if (sourceAsMap == null || !sourceAsMap.containsKey(key)) {
return null;
}
return sourceAsMap.get(key);
}
then:
doc.setCatalog_description(getDescOrNull(sourceAsMap));
am checking for null using ternary operator before am setting the value to my bean class attributes
So I think you need to set multiple bean attributes from the map.
Best and simple solution will be to check null condition on sourceMap for once and then use ternary operator for setting attributes.
if(sourceAsMap != null){
doc.setCatalog_description(sourceAsMap.get("catalog_description") != null ? sourceAsMap.get("catalog_description").toString() : null);
doc.setAnother_description(sourceAsMap.get("another_description") != null ? sourceAsMap.get("another_description").toString() : null);
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
this is my code to check if the value of column is not null
if(!res.getString(res.getColumnIndex("answerquestionid")).trim().equals("")){
but I get this:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
What is the proper way to check if value return by res is empty
Try this,
if(res != null){
if(res.getString(res.getColumnIndex("answerquestionid")) != null && !res.getString(res.getColumnIndex("answerquestionid")).trim().equals(""))
//your stuff
}
Try this:
if(res.getString(res.getColumnIndex("answerquestionid"))!=null){
You have two ways for it:
First is checking if res exists (best approach)
if(res.getIdentifier(myStringName) != 0){
//do stuff
}
Because if it returns 0 it means it doesn't exists.
Second way is checking if string is null
String myRes = res.getString(myStringName);
if(myRes != null && !myRes.trim().equals("")){
//do stuff
}
Your problem was that you were not checking if the String result was null
Hope this helps
You are checking the value of something which may be null, which will throw a Null object reference. to fix this you must check if the String is null.
if (res != null) {
String str = res.getString(res.getColumnIndex("answerquestionid"));
if(str != null) {
// Perform action
} else {
// String is null so recover (use placeholder, try again etc)
}
}
alternativley you can do it in one if statement but I find the above more readable.
if (res != null) {
if( res.getString(res.getColumnIndex("answerquestionid")) != null &&
res.getString(!res.getColumnIndex("answerquestionid")).trim().equals("")) {
//Safe to use String
}
}
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
}
if(string.equals(""))
{
}
How to check if the string is not null?
if(!string.equals(""))
{
}
Checking for null is done via if (string != null)
If you want to check if its null or empty - you'd need if (string != null && !string.isEmpty())
I prefer to use commons-lang StringUtils.isNotEmpty(..)
You can do it with the following code:
if (string != null) {
}
Checking for null is done by:
string != null
Your example is actually checking for the empty string
You can combine the two like this:
if (string != null && !string.equals("")) { ...
But null and empty are two different things
Nothing really new to add to the answers above, just wrapping it into a simple class. Commons-lang is quite all right but if all you need are these or maybe a few more helper functions, rolling your own simple class is the easiest approach, also keeping executable size down.
public class StringUtils {
public static boolean isEmpty(String s) {
return (s == null || s.isEmpty());
}
public static boolean isNotEmpty(String s) {
return !isEmpty(s);
}
}
Use TextUtils Method.
TextUtils.isEmpty(str) : Returns true if the string is null or 0-length. Parameters: str the string to be examined Returns: true if str is null or zero length
if(TextUtils.isEmpty(str)){
// str is null or lenght is 0
}
Source of TextUtils class
isEmpty Method :
public static boolean isEmpty(CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}
if(str != null && !str.isEmpty())
Be sure to use the parts of && in this order, because java will not proceed to evaluating the the second if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.
Beware, it's only available since Java SE 1.6.
You have to check str.length() == 0 or str.equals("")
on previous versions.
As everyone is saying, you'd have to check (string!=null), in objects you're testing the memory pointer.
because every object is identified by a memory pointer, you have to check your object for a null pointer before testing anything else, so:
(string!=null && !string.equals("")) is good
(!string.equals("") && string !=null) can give you a nullpointerexception.
if you don't care for trailing spaces you can always use trim() before equals()
so " " and "" gives you the same result
The best way to check a String is :
import org.apache.commons.lang3.StringUtils;
if(StringUtils.isNotBlank(string)){
....
}
From the doc :
isBlank(CharSequence cs) :
Checks if a CharSequence is empty (""), null
or whitespace only.
You can use Predicate and its new method (since java 11) Predicate::not
You can write code to check if string is not null and not empty:
Predicate<String> notNull = Predicate.not(Objects::isNull);
Predicate<String> notEmptyString = Predicate.not(String::isEmpty);
Predicate<String> isNotEmpty = notNull.and(notEmptyString);
Then you can test it:
System.out.println(isNotEmpty.test("")); // false
System.out.println(isNotEmpty.test(null)); // false
System.out.println(isNotEmpty.test("null")); // true
A common way for testing null string in Java is with Optionals:
Optional.ofNullable(myString).orElse("value was null")
Optional.ofNullable(myString).ifPresent(s -> System.out.println(s));
Optional.ofNullable(myString).orElseThrow(() -> new RuntimeException("value was null"));
And to test if it is null or empty you can use Apache org.apache.commons.lang3 library that gives you the following methods:
StringUtils.isEmpty(String) / StringUtils.isNotEmpty(String): It tests if the String is null or empty (" " is not empty)
StringUtils.isBlank(String) / StringUtils.isNotBlank(String): Same as isEmpty bt if the String is only whitespace it is considered blank
And applied to Optional you get:
Optional.ofNullable(myString).filter(StringUtils::isNotEmpty).orElse("value was null or empty");
Try using Strings.isNullOrEmpty("") from com.google.common.base.Strings this method returns boolean value and checks for both null and empty string.
if(string != null)
or
if(string.length() == 0)
or
if(("").equals(string))
u can try this
if(string != null)