pankaj
pankaj

Reputation: 8348

Unable to throw JSONexception while parsing JSON

I am trying to get some data from a url in my android app. I am using volley library for Get/Post request. Following is my code to get url content:

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(  Request.Method.GET, R.string.login, null,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                    Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                                    startActivity(intent);
                                    finish();
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Log.e("ex","Exception Caught! "+e);
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(jsonObjectRequest);

But I am getting following error in JSONException:

Exception org.json.JSONexception is never thrown in corresponding try block

Upvotes: 0

Views: 745

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191738

Since you used the JsonObjectRequest, there is no need for the try-catch that you would typically see in a StringRequest where you manually would convert the String into a JSONObject.

If there are JSON-parsing errors in the JsonObjectRequest, then you handle that in the onErrorResponse

Upvotes: 1

Rohit5k2
Rohit5k2

Reputation: 18112

org.json.JSONexception is thrown only on JSON operation. Your try block has no JSON operation so this error would never be thrown.

Either Change org.json.JSONexception to java.lang.Exception or remove the try-catch block altogether.

try {
    Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
    startActivity(intent);
    finish();
} catch (Exception e) {
    e.printStackTrace();
    Log.e("ex","Exception Caught! "+e);
}

Upvotes: 3

Related Questions