0

my app sends a POST request to a server and gets a response using JSON format.

Sometimes my JSON response is "null" (if the request goes in time out). In that case I need to notify the user about the timeout (dialog or toast) and avoid the app to crash.

How do I handle correctly the JSONException and avoid the app crash?

Thank you! Marco

2
  • Unless I'm missing something you're asking how do you catch an exception and show a dialog box? Commented Oct 5, 2011 at 18:22
  • Is there a reason a try-catch block wouldn't suffice? Commented Oct 5, 2011 at 18:23

3 Answers 3

3

to avoid the crach of your app while parsing your json , try this :

if (jsonResponse == null) {
       // notify user
} else {
      try {
         // parse json here.
      } catch (JSONException e) {
        Toast.makeText(this,"Error on the response", 3000).show();
      }


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

Comments

1

check if your json response is null. only then parse the json.

if (jsonResponse == null) {
       // notify user
} else {
      // parse json here.
}

Comments

0

get full exception :

StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        jsonString = out.toString();
    }

    }catch(ConnectException e){             
    // handle your exception here, maybe something like
        Toast.makeText(context,"Error!",5000).show();
        finish(); 

    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

Comments

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.