checking a string for null in java - java

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)

Related

Why the retrieved result set string doesn't work with the .equals()

I'm retrieving some information from a database and I want to check if the value is null. Although the string retrieved from the database is "null" the equals() returns false.
I tried trim(), just in case there were any spaces in the retrieved string
String code = product.retrieveCode();
System.out.println("the code is :"+ code);
if (code.equals("null")==true){
// do this
}
else{
// do that
}
Please let it be noted that the database doesn't have any data stored.
As pointed out by 'Eran', the value in code is probably a null reference. Do,
if (code == null)
instead of
if (code.equals("null")==true)
This likely occurs because the rs object returns null when you call it's getString() method. ResultSet will return null when the column value is SQL NULL. (Reference)
your logic and syntax is correct.In this case here your database value is probably assigning null value to code and you are checking whether a string of "null" is equal to code. This will give error as it is null reference. Make sure that you are getting a "null" else if its empty just check equals case withe whitespace
It prints Yes. so I don't think java doing anything wrong
String code = "null";
if (code.equals("null")){
System.out.println("Yes");
} else{
// do that
}
I think it is a null reference. Please do the below code.
if (code==null){
System.out.println("Yes");
} else{
// do that
}

Checking if Parse.com class is (undefined)

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.
}

!array[0].isEmpty() returning NullPointer?

Here's my code:
if (!quizDescs[0].isEmpty()) {
mDescText.setText(quizDescs[0]);
} else {
mDescText.setVisibility(View.INVISIBLE);
}
So, when this code runs, and the if condition returns true, everything is fine and dandy, however, if it returns false, it says there's a NullPointerException, and points me to the line of code containing the if statement.
Am I checking the condition right? Why is it returning a NullPointer?!
ANSWER:
if (quizDescs[0] == null) {
mDescText.setVisibility(View.INVISIBLE);
} else {
mDescText.setText(quizDescs[0]);
}
if quizDesc[0] is String, you can do
if(!StringUtility.isEmptyOrNull(quizDesc[0])){
mDescText.setText(quizDescs[0]);
}else {
mDescText.setVisibility(View.INVISIBLE);
}
By the way,
Null and being empty is not same
Consider
String s; //Initialize to null
String a =""; //A blank string
Its always a good practise to use
try{
//Your code here..
}catch(Exception e){
e.printStacktrace();
}
If either quizDescs or quizDescs[0] are null, you'll get a NullPointerException.
Obviously, if isEmpty() returns false, it means that isEmpty() was executed, so quizDescs[0] is not null when the condition returns true, and that's why it works.
Either make sure that both quizDescs and quizDescs[0] is never null, or change the condition to :
if (quizDescs != null && quizDescs[0] != null && !quizDescs[0].isEmpty()) {
....
} else {
....
}
You have an error because quizDescs is Null so when you try to get quizDescs[0] in the condition, you try to get the first item of null object.
The only possible ways the if-line can cause a NullPointerException, is when quizDescs itself is null or the first element quizDescs[0] is null. Try to extract quizDescs into a local variable for debugging purposes and inspect its content.
You can either initialize your array with empty strings or add a check for null - or better review your logic how null is a possible condition. Usually null values should be avoided (see Bloch, Effective Java 2nd Edition, item 43 for a similar case).

What happens when a method returns null

I am new to Java, and need to figure out process when a method return null and reference variable.
Here is the code of the method:
public Lot getLot(int lotNumber)
{
if((lotNumber >= 1) && (lotNumber < nextLotNumber)) {
// The number seems to be reasonable.
Lot selectedLot = lots.get(lotNumber - 1);
// Include a confidence check to be sure we have the
// right lot.
if(selectedLot.getNumber() != lotNumber) {
System.out.println("Internal error: Lot number " +
selectedLot.getNumber() +
" was returned instead of " +
lotNumber);
// Don't return an invalid lot.
selectedLot = null;
}
return selectedLot;
}
else {
System.out.println("Lot number: " + lotNumber +
" does not exist.");
return null;
}
}
What happens when a method returns null and reference variable, while having a class data type?
Please explain in easy words.
null is valid value for any Object in Java. Since Lot is also a Java object. null is valid.
But
If you are not careful you may end up with NullPointerException.
Eg:
Lot lot=someInstance.getLot(2); // say lot is null
Then
String something=lot.getThis(); // here is null.getThis()
You will end up NullPointerException here.
You need to handle with care these cases to avoid NullPointerException.
Eg:
Lot lot=someInstance.getLot(2);
if(lot!=null){
String something=lot.getThis();
}
Null in java means, that your instance (variable) contains no object. You can use it, but you must not call any method on that object, because If you did so, you'd get a NullPointerException.
When null is returned from a method, it usually means that the method was not able to create a meaningful result. For example the method, that reads data from database was not able to find the specified object or some error occurred during the method run.
If a method can return null, then you should check the result before further processing like. See the example of raising a sallary of an employee:
Employee e = database.getEmployeeById(1);
if (e==null) //this is the check
{
System.out.println('There is no such employee');
}
else
{
e.setSallary(e.getSallary() * 1.1);
}
Since null is a value, your program will compile fine.
But depending in the situation you are using a null variable you may end up with NullPointerException while running your app.

JSONObject when element doesn't exist

I have a struts action receiving following JSON:
{
"commandId":"tC",
"id":"123",
"def":""
}
Following code works just fine:
JSONObject command = null;
String commandId = null;
String deviceId = null;
try {
command = new JSONObject(json);
commandId = command.getString("commandId");
}
Since "def" can be empty, non declared or can contain another array of elements I tried doing this:
JSONObject def = command.getJSONObject("def");
in order to get this JSON object defined in the element def
This only works if def isn't empty like in this example:
{
"commandId":"tC",
"id":"123",
"def":{"1":"aaa", "2":"bbb"}
}
When def is empty or not defined my program stops working on the line JSONObject def = command.getJSONObject("def"); and noticed that it doesn't continue the execution?!
If I put JSONObject def = command.getJSONObject("def"); try / catch block I get _JSONObject["def"] is not a JSONObject _ exception, but execution doesn't continue
How does JSONObject.getJsonObject(String) behave?
I would expect it to return an empty JSONObject and continue the execution.
What I want is to check if there is anything defined in def and then in a if, else decide what to do in my program according to the value found there... I can't find a way to make my program work if a client's json comes with def empty or not defined.
my suggestion is to define "def" either be defined as null or {}:
"def":null or "def":{} to align with its usage agreement
quotes is really just used to indicate the value is a string. following the standard might save you and others from confusion in the future.
Likely it is because it is trying to get a Object and finding a string. In your JSON (if you control it), for an empty object I would do {}. This should allow Java to think it is retrieving an object.
If def is intended to be an object is it not suppose to look like this when empty?
{
"commandId":"tC",
"id":"123",
"def":{}
}
I think having "def":"" will cause the value to be attempted to be parsed as a string value and not an object value.
Maybe this will help someone. I had to solve the same problem. In my case the web service was returning empty JSON objects if it couldn't find the requested record.
Note: the data names have been changed to protect the innocent...
Note 2: this example uses javax.json
import javax.json.*;
JsonObject _jObj = _myRootObj.getJsonObject("someDataNode");
// at this point in execution _jObj could equal {"DataReturn":""}
// or {"DataReturn":"<some valid data>"}
// we want to test the existence of DataReturn before trying to
// use it
JsonValue jv = _jObj.getOrDefault("DataReturn", null);
String js = jv.toString();
// cover all the bases. test the value
if (js == null || js.isEmpty() || js.compareTo("\"\"") == 0)
{
throw new Exception("Error: DataReturn object null. Cannot proceed.");
}
// the object exists, so it's ok to get it
JsonObject jObjDate = _jObj.getJsonObject("DataReturn");
If you're using org.json.JSONObject you can use .isNull(String key) to do this, something like:
if (command.isNull("def") {
// Handle 'def' not being there
} else {
JSONObject def = command.getJSONObject("def");
}

Categories

Resources