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.
}
Related
I need specific data for a report, then I gettin all information from a parent object
Object1
It has many attributes, object attributes
Object11, Object12, Object13, attr1, attr2...
The attributes has many attributes too
Object111, Object131, Object132,..
by now I got 5 level data attributes.
When I send information to my report it says, Error: cause:null
object1.getIdObject11().getIdObject111().getDescription;
It trows error because Object111 is null
I tried using
object1.getIdObject11().getIdObject111().getDescription==null?'':object1.getIdObject11().getIdObject111().getDescription;
but it only verify if description is null, and throws the same error
Then I tried to verify Object
if(object1.getIdObject11().getIdObject111() == null) {
var = object1.getIdObject11().getIdObject111().getDescription;
} else {
var = "";
}
But when Object11 is null, it throws same error.
I don't think its a good way doing this for each attribute (have to get like 30 attributes)
if(object1.getIdObject11()!=null) {
if(object1.getIdObject11().getIdObject111()!=null) {
if(object1.getIdObject11().getIdObject111().getIdObject1111()!=null) {
//...
}
}
}
I want to verify if is there a null object and set '' (blank) if it is, with no such a large code(because the gotten params are set inside a report, mixed with letter).
reportline1 = "Area: "+object1.getIdObject11().getIdObject111().getName;
You code breaks Demeter's law. That's why it's better to refactor the design itself.
As a workaround, you can use Optional
var = Optional.ofNullable(object1)
.map(o -> o.getIdObject11())
.map(o -> o.getIdObject111())
.map(o -> o.getDescription())
.orElse("")
The way I would probably do this to extend the functionality of the code easily in the future might take a bit of writing in the beginning but will be easily usable forever.
I would create a new method in your parent class called hasNull that returns a boolean like so:
public boolean hasNull()
{
boolean hasANull = false;
//Call another hasNull() inside of object11 which in turns calls hasNull() in object111 etc.
//If any of the calls return with a true/null value set hasANull to true
return hasANull;
}
This in turn checks to see if the current objects it contains are null. If one of the class variables is another custom class you created you can then add another hasNull into that one and keep going until you get to the lowest level where you can do a specific operation when the value is null such as set it to "".
After implementing this you will be able to just be able to use it like this any time you need it:
if (!object1.hasNull())
{
//Do whatever you want if there are no null values
}
else
{
//Do whatever you want if there is a null value
}
You can also make this a void method if you only want it to toggle the values on the lowest level, and do not need to do anything in either case.
I prefer the solution that gave dehasi.
But you can also do something like that:
getOrElse(() -> object1.getIdObject11().getIdObject111().getDescription(), "")
Where getOrElse is:
public static <T> T getOrElse(Supplier<T> getter, T elseValue) {
try {
return getter.get();
} catch (Exception e) {
// log or do something with it
}
return elseValue;
}
It may be controversial becaouse you use Exception to do this.
You can use this code to check if your object has a null attribute, the object is myclass;
for (Field f : myclass.getClass().getDeclaredFields()) {
f.setAccessible(true);
try {
if (Objects.isNull(f.get(myclass))) {
isLineContainsNull = true;
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
There is a possiblity that this may be a dupicate question.
I initialize a String variable to null.I may or may not update it with a value.Now I want to check whether this variable is not equal to null and whatever I try I get a null pointer exception.I can't afford to throw nullpointer exception as it is costly.Is there any workaround that is efficient.TIA
If you use
if (x == null)
you will not get a NullPointerException.
I suspect you're doing:
if (x.y == null)
which is throwing because x is null, not because x.y is null.
If that doesn't explain it, please post the code you're using to test for nullity.
I guess you are doing something like this,
String s = null;
if (s.equals(null))
You either check for null like this
if (s == null)
A better approach is to ignore the null and just check for the expected value like this,
if ("Expected value".equals(s))
In this case, the result is always false when s is null.
String is immutable
#Test(expected = NullPointerException.class)
public void testStringEqualsNull() {
String s = null;
s.equals(null);
}
#Test
public void testStringEqualsNull2() {
String s = null;
TestCase.assertTrue(s == null);
}
I am comparing s==null only
can you show the code snippet that you have written
s==null will never throw a NPE
if you are checking whether "s" is null, then do not apply a dot(.) after "s". Doing that would throw NullPOinterException, as applying dot(.) means that you are trying to access on a pointer location which is basically null at the moment !
Also try to use library functions that check whether a string is null or empty. you may use StringUtils.isEmpty(s) from apache library which checked both
I have this:
String object = "";
try {
object = data.getString("url");
System.out.println("Url Object:" + object);
}
catch (JSONException e) {
e.printStackTrace();
}
System.out.println("object is:" + object);
if (object!= null ) {
// doSomething
} else {
// is Null
}
and although this is printed:
object is: null
The code enters the if condition and not the else.
What am I missing?
EDIT: where data is a JSONObject. I now want to test the case that url is null. Therefore, I know that data is null and I can see it printed.
Your code is an anti pattern. Move the code that processes 'string' inside the 'try' block. Don't just catch exceptions and then continue as though they didn't happen, and have to sort out again whether you're in a valid state. That's what the 'try' block is for. If you're still in it, you're in a valid state.
Please note that getString(..) is returning "null" (as a String, when ob.toString() do that). So when you assign it to object, it is a String: "null", not null.
To correct your code one way would be:
if (!object.equals("null")) {
// doSomething
} else {
// is Null
}
Another solution would be setting object to be null if getString() returns "null":
if (data.getString("url").equals("null"))
object = null;
Don't initialize your String object to "" if you want it to be null if the json parsing bits fail.
Change your top line to:
String object = null;
More to the point, check out https://stackoverflow.com/a/21246501/599075
The only explanation to your case is that the data.getString("url"); is returning a "null" String value.By the way I recommend you these points :
Initialize your object by a null reference (String object = null;)
Change the if condition (if(object!=null) && !object.isEmpty())
Otherwise, try to print entirely the content of the data object to the console so you can check the json content you are trying to parse.
(Sorry if I made some language mistakes)
Here is a simple code snippet and I cannot figure out why does it throw a NullPointerException.
String lastGroup = "";
menuTevekenysegekGrouped = new ArrayList<MenuElem>();
for(MenuElem me : menuA) {
// double checked that me objects are never null
// double checked that menuA is never null
if(me.getGroup() != null && !me.getGroup().equals(lastGroup)) { /* NPE!!! */
lastGroup = me.getGroup();
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
In the first iteration the me.getGroup() returns null. So the first operand of the && is false and second operand should not evaluate according to the JLS, as far as I know. However when I debug the code I get NPE from the marked line. I'd like to know why. (Using JRockit 1.6.0_05 if it matters..)
Are you sure that me itself is not, in fact, null?
From your code (without the stacktrace I have to guess), the following may be null and be the cause: menuA or me or menuTevekenysegekGrouped. And some of the values returned from the methods/or used in the methods may also be null, but it's hard to know...
If me is not null, then the only other object that can be null in the above snippet is menuTevekenysegekGrouped. Add a check before first using it to ensure that it's not null.
The repeated calls to me.getGroup() would bug me enough to pull them out into a local variable:
String lastGroup = "";
for(MenuElem me : menuA) {
String thisGroup = me.getGroup();
if(thisGroup != null && !thisGroup.equals(lastGroup)) {
lastGroup = thisGroup;
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
This is only going to fix your problem if in fact me.getGroup() returns different values (sometimes null) on multiple calls with the same me, but it might make it easier to debug, and certainly makes it easier to read.
I am struggling with this error. I feel its really simple but cannot understand why am getting the error.
I keep getting a NullPointerException when I iterate through values in my linked list.
Code Snippet:
private void updateBuyBook(LimitOrder im) {
LimitOrder lm = null;
Iterator itr = buyBook.entrySet().iterator();
boolean modify = false;
while (itr.hasNext() && !modify) {
Map.Entry pairs = (Map.Entry) itr.next();
if ((((LinkedList<IMessage>) pairs.getValue()).size() > 0)) {
LinkedList<ILimitOrder> orders = (LinkedList<ILimitOrder>) pairs
.getValue();
ListIterator listIterator = orders.listIterator();
while (listIterator.hasNext() && !modify) {
LimitOrder order = (LimitOrder) listIterator.next();
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) { // error at this line
lm = order;
addToBuyMap(im);
modify = true;
break;
}
}
if (modify = true) {
orders.remove(lm);
break;
}
}
}
}
Error is at this line:
Exception in thread "main" java.lang.NullPointerException
order.getOrderID().equalsIgnoreCase(im.getOrderID()));
Please help. Is my assignment wrong in any way???
Please help!!!
Thanks
Changing your code a bit will make it longer, but much easier to find the error... instead of doing:
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) {
Change it to:
String orderID = order.getOrderID();
String imOrderID = im.getOrderID();
if(orderID.equals(imOrderID()) {
Then you will know if order or im is null. If neither of those is null then the things that could be null are orderID and imOrderID. It is now a simple matter of finding out which one of those is null.
If it is order or im then the program will crash on the order.getOrderID() or im.getOrderID() lines.
If, instead it is orderID or imOrderID that is null, then it will crash on if(orderID.equals(imOrderID()) {. You can then use System.out.println (or something better, like a debugger) do easily find out what is wrong.
If neither of those should be null then I suggest adding something like:
if(orderID == null) { throw new IllegalStateException("orderID cannot be null"); }
if(imOrderID == null) { throw new IllegalStateException("imOrderID cannot be null"); }
and then track down how it got set to null to begin with.
My guess would be that you're passing in the null, into im. I'll need to see more of the code to be sure.
You never check to see if im is null. I suspect it is.
One first look, where is im instantiated? You can also try to debug in your IDE so as to see whats going on?
Either im is null or order.getOrderID() is returning null.
Doesn't look like im is ever declared / assigned. So
im.getOrderID()
is probably where the null pointer exception is generated.
-- Dan
Edit:
Missed that im is passed in as an argument. So that leaves a few possibilities (in order of likelihood):
im is null (ie. user called function with null parameter)
order.getOrderID() is returning null
order is null (ie. the list has nulls in it)
Edit2:
Your line
if (modify = true)
Is fundamentally wrong and will always evaluate to true (single equal is for assignment, == is for comparison.)
When simply checking if a flag boolean is true or false, it is best to use:
boolean flag = true;
if(flag)
{
// True block
}
else
{
// False block
}
It will be good if you could add a debug point before that line and see which variable is null. looking at the code the answer is 1. order is null 2. order.getOrderID() is null or 3. im is null