I want to handle when my json receive NULL data from my host. But the if conditions never happens when my json is null (I unplugged the internet conection to receive null data). See my code:
JSONObject json = null;
JSONObject json2 = null;
JSONObject json3 = null;
date= (String.valueOf(anio)) + "-" + (String.valueOf(mes + 1)) + "-" + (String.valueOf(dia));
try {
json = JSONParser.readJsonFromUrl(url1.concat(date)));
json2 = JSONParser.readJsonFromUrl(url2.concat(id));
json3 = JSONParser.readJsonFromUrl(url3.concat(date));
} catch (IOException | JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if(json == null || json2 == null || json3 == null){
String mensajeAlerta = "Verifique su conexión a internet...";
Intent intent = new Intent(MyActivity.this, SecondActivity.class);
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("mensajeAlerta", mensajeAlerta);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
EDIT: JSONParser class
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
return new JSONObject(jsonText);
} finally {
is.close();
}
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
Thanks for helping!
Aucun commentaire:
Enregistrer un commentaire