Search code examples
androidjsonexception

JSONException not caught


I have this piece of code:

HJRestClient.post(path, params, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {

            try {
                JSONArray array = response.getJSONArray("tags");
                if (adDetailViewAdapter != null) {
                    adDetailViewAdapter.setTags(array);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });

It is crashing on the line JSONArray array = response.getJSONArray("tags"); with exception W/System.err: org.json.JSONException: No value for tags

While I have written code for catching the exception, it's not getting caught and causing the app to crash.

I have 2 devices Samsung Galaxy Note 5 with Android v6.0.1 in which the exception is caught successfully.

Another Huawei Mate 7 with Android v4.4.2 in which the exception is not getting caught and causing a crash.

I also wrote:

catch (Exception exception) {}

but still it's getting crashed.

Any help?


Solution

  • You should this way:

    HJRestClient.post(path, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    if(response!=null&&response.has("tags")){
                        JSONArray array = response.getJSONArray("tags");
                        if (adDetailViewAdapter != null) {
                            adDetailViewAdapter.setTags(array);
                        }
                    }
    
                } catch (JSONException e) {
                    e.printStackTrace();
                }
    
            }
        });
    

    Hope this will help you.