androidandroid-volleyandroid-webservice

Unable to compare the JSON String Response in the “if” Statement in android using volley library


I am getting JSON String Response in a string variable. I want to compare it in the “if” statement. But program cannot go to the “if” statement. But it shows the response in the TextView.

Here is my if statement

  if (myObjAsString == "WRONG_PASS_ERROR") { //USER_EXISTS_ERROR //WRONG_PASS_ERROR

                                Toast.makeText(MainActivity.this, "Login Invalid", Toast.LENGTH_LONG).show();
                            }

Here is my code.

String url = "http://someexample.com/signin.php";
        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {


                            JSONObject jsonResponse = new JSONObject(response);
                            String myObjAsString = jsonResponse.getString("type");

                            if (myObjAsString == "WRONG_PASS_ERROR") { //USER_EXISTS_ERROR //WRONG_PASS_ERROR

                                Toast.makeText(MainActivity.this, "Login Invalid", Toast.LENGTH_LONG).show();
                            }

                            mTV.setText(myObjAsString);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                // the POST parameters:
                params.put("email", "example@outlook.com");
                params.put("password", "*****");
                return params;
            }
        };
        Volley.newRequestQueue(this).add(postRequest);

Solution

  • Use equals. Objects comparison is done like this in java.

    if (myObjAsString.equals("WRONG_PASS_ERROR"))

    or even this will protect from npe:

    if ("WRONG_PASS_ERROR".equals(myObjAsString))