2016-11-16 117 views
3

在Android應用程序中,我需要檢查JSON響應是否爲空。 這是我的代碼:Android檢查JSON響應是否爲空

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); 
    } 
} 

我有嘗試:

if (nombre.isEmpty()) { 

if (nombre == null) { 

if (nombre == "") { 

但應用始終顯示,如果條件的其他部分。 如果沒有從JSON數據輸出始終是:

通訊社:空 Direccion空 Codigo:空

如果有數據,輸出的是正確的輸出。 歡迎任何幫助

回答

3

在android中使用TextUtils.isEmpty()來檢查null。 但我認爲你的情況nombre不是null。
String nombre =「null」;很可能在你的情況下。

+0

你說得對,在我的情況下,nombre ==「null」是正確的。謝謝, – mvasco

+0

很高興幫助! ;-) –