开发者

Android parse JSON and avoid app crashing if JSONException

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 cr开发者_StackOverflow中文版ash.

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

Thank you! Marco


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


}


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

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜