I am working on an android app that get json content of a webservice called \"WebUntis\". The Json content i am getting looks like:
{\"jsonrpc\":\"2.0\",\"id
You can also use isEmpty()
method, this is the method we use to check whether the list is empty or not. This method returns a Boolean value. It returns true if the list is empty otherwise it gives false. For example:
if (!k1.isEmpty()) {
klassenID[i] = kl.getJSONObject(0).getString("id");
}
You can use the regular length() method. It returns the size of JSONArray. If the array is empty, it will return 0. So, You can check whether it has elements or not. This also keeps you in track of total elements in the Array, You wont go out of Index.
if(k1 != null && k1.length != 0){
//Do something.
}
This is another way to do it...
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call,
Response<JsonObject> response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(new Gson().toJson(response.body()));
JSONArray returnArray = jsonObject.getJSONArray("my_array");
// Do Work Only If Not Null
if (!returnArray.isNull(0)) {
for (int l = 0; l < returnArray.length(); l++) {
if (returnArray.length() > 0) {
// Get The Json Object
JSONObject returnJSONObject = returnArray.getJSONObject(l);
// Get Details
String imageUrl = returnJSONObject.optString("image");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<JsonObject> call,
Throwable t) {
}
});
If the array is defined in the file but is empty, like:
...
"kl":[]
...
Then getJSONArray("kl")
will return an empty array, but the object is not null
. Then, if you do this:
kl = c.getJSONArray("kl");
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
kl
is not null
and kl.getJSONObject(0)
will throw an exception - there is no first element in the array.
Instead you can check the length()
, e.g.:
kl = c.getJSONArray("kl");
if(kl != null && kl.length() > 0 ){
klassenID[i] = kl.getJSONObject(0).getString("id");
}