7

I am getting this LogCat:

06-22 15:30:53.731: E/AndroidRuntime(2389): java.lang.NumberFormatException: Invalid float: "null"
06-22 15:30:53.731: E/AndroidRuntime(2389):     at java.lang.StringToReal.invalidReal(StringToReal.java:63)
06-22 15:30:53.731: E/AndroidRuntime(2389):     at java.lang.StringToReal.parseFloat(StringToReal.java:310)
06-22 15:30:53.731: E/AndroidRuntime(2389):     at java.lang.Float.parseFloat(Float.java:300)
06-22 15:30:53.731: E/AndroidRuntime(2389):     at java.lang.Float.valueOf(Float.java:337)

Here is code:

try
{
    jObject = new JSONObject(result);
    starAvg = jObject.getString("AverageRating"); 
}
ratingsBar = (RatingBar) findViewById(R.id.theRatingBar);
ratingsBar.setRating(Float.valueOf(starAvg));

Here is the context:

In PHP, I am averaging total numbers in a column in a MySQL table. When there are ANY rows, it will send back an average of the data in it and it encodes it, and Java picks it up as a JSON object. But sometimes, there are cases where a table may have 0 rows, so I get this JSON Object:

 {"AverageRating":null}

My app then crashes and the LogCat is as seen above.

The String doesn't seem to care if it picks up a Null JSON Object but the app crashes when I do Float.valueOf(theString).

Another side note, I have tried to test this way:

if String is Null, Float = 0 
if String is not null, Float.valueOF(String)

But it doesn't ever seem to read the String as null. Is it actually NOT null in this case?

0

4 Answers 4

26

Use the following method of JsonObject to check if a value against any key is null

public boolean isNull(java.lang.String key)

This method is used to check Null against any key or if there is no value for the key.

Use below snippet

if (jsonObject.isNull("AverageRating")) {
    Toast.makeText(this, "Cannot Convert!!", Toast.LENGTH_LONG).show();
    //float set to 0
} else {
    Float.valueOf(jsonObject.getString("AverageRating"));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Vipul.isGenius(Shah) ? +1 : null
Upon further evaluation, I am moving this answer to the correct one.
4
String str = jObject.getString("AverageRating");
float number = 0.f;
try
{
    number = Float.parseFloat(str);
}
catch (NumberFormatException e)
{
    number = 0;
}

parseFloat() will throw an exception if it receives null.

8 Comments

1. don't use exceptions to process non-exceptional conditions 2. don't catch the base class Exception.
it's a design issue. exceptions are for exceptional conditions ... things you don't expect to happen during normal operation of the code. this is just a guideline, and you are often forced to violate this by poor API design. in this case, the entity generating the JSON should either add a number (not a string, not a null object), or leave the field blank if the field is optional.
I guess you're right. That sounds reasonable. I'm sorry I didn't thought of that a bit before. It now occurs to me; there could be >0 rows and yet the average could be 0. null as a return value clearly is an exception and should be handled appropriatelly.
@JeffreyBlattman, this is just a religious objection. There is no universal definition of what constitutes exceptional. Furthermore, the poster did not give us the information to determine whether having 0 rows is an exceptional condition or not. He/she merely acknowledged that it's a case that must be handled. Depending on the actual application, the performance cost of catching an exception may very well be negligible. Propagating general rules about not using exceptions is throwing the baby out with the bathwater. Exceptions can be a very useful language feature.
@Nate yes, that's why i said in the answer that i wrote that this only applies if receiving a null value is exceptional. i wouldn't call it religious, i'd call it purist.
|
0

check for null before you parse the value,

String s = jObject.getString("AverageRating");
if (s != null) {
  double rating = Double.parseDouble(s);
  // whatever
}

that being said, if the value of AverageRating is really a number, then the entity that is generating the JSON shouldn't add it to the JSON as a string. if there's no value for the field, the field should be absent. if there's a value for the field, it should be a number.

if that were true, you could handle it like this,

if (jObject.has("AverageRating")) {
  double rating = jObject.getDouble("AverageRating");
  // whatever
}

other posts have suggested simply catching NumberFormatException. this is only correct if you expect to have a valid double value in the field at all times and consider it exceptional otherwise. if you know / expect that the field will some times be absent, it does not qualify as an exceptional condition.

Comments

0
if (json != null && json.getString(KEY_SUCCESS) != null){
    // PARSE RESULT 
}else{
    // SHOW NOTIFICIATION: URL/SERVER NOT REACHABLE
}

that being said check null value like key as json value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.