3

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You are right, In my case nombre == "null" is right. Thank you,
Glad it helps! ;-)

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.