0

I think that JSONException only works when it my request fails but when the request is valid (valid username, password) it should redirect me to another activity but instead a JSONException is showing up.

It shows the JSON string received from the server rather than redirecting me to another activity.

This is my onResponse function

        @Override
        public void onResponse(String response){
            try {
                JSONObject volleyResponse   = new JSONObject(response);

                boolean success       = volleyResponse.getBoolean("success");
                String message        = volleyResponse.getString("message");

                String UUID     = volleyResponse.getString("unique_user_id");
                String LLOGIN   = volleyResponse.getString("last_login");
                String RDATE    = volleyResponse.getString("registration_date");
                String MONEY    = volleyResponse.getString("money");

                if(success){
                    Intent intent = new Intent(Authentication.this, Mainpage.class);
                    intent.putExtra(KEY_USERNAME, strUsername);
                    intent.putExtra(KEY_UUID, UUID);
                    intent.putExtra(KEY_LLOGIN, LLOGIN);
                    intent.putExtra(KEY_RDATE, RDATE);
                    intent.putExtra(KEY_MONEY, MONEY);
                    startActivity(intent);
                }
            } catch(JSONException e) {
                response = response.replace("\"", "");
                response = response.replace("status:false,message:", "");
                response = response.replace("{", "");
                response = response.replace("}", "");
                messageText.setText(response);
            }
        }

JSON Response when it is success:

{"unique_user_id":"4e99a28a-0cb2-30a9-ac51-ccd4629bcef1","last_name":"therealaxis","password":"$2a$10$9qRjW\/vJreCQg3u5dO6eW.8PhZBTpGaPNK5qRIYP.XTx2PVY1yrOi","last_login":"1 week ago","registration_date":"1 week ago","money":"100.00","success":true}
  • Your reponse has no message string, so a JSONException is thrown – peterulb Jun 04 '17 at 18:50
  • It has a message string when it failed, but on success it just shows you your stats, and a true [boolean] success key. –  Jun 04 '17 at 18:54
  • Yes, but you always try to access the message attribute. Even if it succeeded. At that point, it directly jumps in your catch block – peterulb Jun 04 '17 at 18:55
  • I'm gonna test it right now, thanks :) [post it as an answer tho] –  Jun 04 '17 at 18:56

1 Answers1

0

Your JSON Response has no message string, so a JSONException is thrown. If you just want to access the message attribute in case it is present, use JSONObject.has before accessing it.

peterulb
  • 2,869
  • 13
  • 20