0

I am developing an Android Application which Fetch data from PHP Json.

I fetch the data of json successfully From JSON but my problem is when JSON is Empty it stops the application.

So I need to Know is How to know if the JSON is NULL or Return Nothing in ANDROID.

My empty JSON is:

[[]]

How to check that with Coding.

Please send me your suggestions.

My Full Code is On This Link:

Thanks Alot

Community
  • 1
  • 1
Nirav Dabhi
  • 341
  • 1
  • 7
  • 29

5 Answers5

2
JSONObject myJsonObject = 
    new JSONObject("{\"null_object_1\":[],\"null_object_2\":[null]}");

if (myJsonObject.getJSONArray("null_object_1").length() == 0) {
    ... 
}
Abhinav
  • 8,028
  • 12
  • 48
  • 89
2

firstly you get key set of json.

 Iterator<Object> keys = json.keys();

then check if any key exist then your json contain some value.

if(keys.hasNext()){ // json has some value

} else { // json is empty. }

Yogendra
  • 4,817
  • 1
  • 28
  • 21
1

try like this,

if (<Your JSONobj>!= null ){
    // do your parsing 
}else{

}
Balder
  • 8,623
  • 4
  • 39
  • 61
Aerrow
  • 12,086
  • 10
  • 56
  • 90
  • I m parsing the data from JSON to listview so if I check this condition first i initialise jsonobj=null; then how it works – Nirav Dabhi Apr 05 '14 at 05:58
1

after getting json from url first check for null by simply execute the code:-

if(yourjsonobject!=null){

//write your code here

}else{e
enter code here
//json is null
}
Abhinav
  • 8,028
  • 12
  • 48
  • 89
1

1) json string "[[]]" means not empty jsonAarray it means your Outer JsonArray contains one element as JsonArray and your inner JsonArray is empty.

2) The reason your application is crashing/stopping is that JsonObject and JsonArray are incomptible types. You can not cast JsonArray to JsonObject. See JsonArray and JsonObject

3) You can always check the length of your JsonArray by JsonArray#length() method. also check JsonArray#isNull if want to check wheter a JsonObject is NULL.

try {
    JSONArray object = new JSONArray("[[]]");
    if (object.length() > 0) {
        JSONArray inner = object.getJSONArray(0);
        if (inner.length() > 0) {
        // do something         
        }
    }           
} catch (JSONException e) {
    e.printStackTrace();
}
vijay_t
  • 776
  • 6
  • 14