mvasco mvasco - 18 days ago 5
JSON Question

Android check if JSON response is null

In an Android App I need to check if a JSON response is null.
This is my code:

private void showJSON(String response) {
String nombre = "";
String direccion = "";
String codigo = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
nombre = collegeData.getString(Config.KEY_NAME);
direccion = collegeData.getString(Config.KEY_ADDRESS);
codigo = collegeData.getString(Config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}

if (nombre.isEmpty()) {
nombre = "AGENCIA NO ENCONTRADA";
textViewResult.setText("Agencia:\t" + nombre);
}
else {

textViewResult.setText("Agencia:\t" + nombre + "\nDireccion:\t" + direccion + "\nCodigo:\t" + codigo);
}
}


I have tried with:

if (nombre.isEmpty()) {

if (nombre == null) {

if (nombre == "") {


But the app always shows the else part of the if condition.
And the output if there are no data from JSON is always:

Agencia: null
Direccion null
Codigo: null

If there are data, the output is the right output.
Any help is welcome

Answer

In android use TextUtils.isEmpty() to check null instead. But I think in your case nombre is not null.
String nombre = "null"; likely in your case.

Comments