lutakyn
lutakyn

Reputation: 474

String Request To Post not showing any error

I am making a post request in Android studio using string request, when I debug,i get no error. I don't get the JSON object in the code when i debug. It skips the login request and debug is ended.if I'm not doing something correct.please try and correct it

This is the JSON object

{"RESPONSECODE":200,
"RESPONSEDATA:[{"id_User":"120","FirstName":"King",
"LastName":"Dosty","Role_Id":"2","Email":"[email protected]","location":null,"Password":"$2y$10$fJJH6qOuhhXaDadHQhZefemBwHPZ3aHid\/WF579DwVJo8XyVGaEN6",
}],"Success":true}

This is the loginRequest java class

public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://localhost/project/index.php/clientapinew/post_login2";
private Map<String, String> params;
public LoginRequest(String Email,String Password, Response.Listener<String> listener){
    super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
    params = new HashMap<>();
    params.put("Email", Email);
    params.put("Password", Password);
}
@Override
public Map<String, String> getParams(){
    return params;
}
}

This is the login button to sent the request on click in the activity

 loginBtn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
   String Email = emailEdt.getText().toString();
   String Password = passwordEdt.getText().toString();
   LoginRequest loginRequest = new LoginRequest(Email, Password, 
   new Response.Listener<String>() {
    @Override
      public void onResponse(String response) {
      try {
     JSONObject jsonResponse = new JSONObject(response);
     Log.d(TAG, jsonResponse.getString("SUCCESS"));
     boolean success = jsonResponse.getBoolean("SUCCESS");                            
    if (success) 
    {
   Intent intent = new Intent (LoginActivity.this,MainActivity.class);
    startActivity(intent);
    Toast.makeText(LoginActivity.this, "Login  Successful", 
   Toast.LENGTH_SHORT).show();}            
    else {
    AlertDialog.Builder builder = new 
     AlertDialog.Builder(LoginActivity.this);
     builder.setMessage("Login Failed").setNegativeButton("Retry", null)
    .create().show();             
     }
     } 
   catch (JSONException e) 
   {  e.printStackTrace();}}
    });
    RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
   queue.add(loginRequest);

        }
    });

This is the url get and the params when i debug

[ ] localhost/project/index.php/clientapinew/post_login2 0x59c3b57d NORMAL null Email : [email protected] Password: azerty

Upvotes: 1

Views: 1386

Answers (2)

Wasim Abuzaher
Wasim Abuzaher

Reputation: 814

I'd suggest you ditch the LoginRequest Class, and add this method in your LoginActivity:

private void login(final String email, final String password){
        String LOGIN_REQUEST_URL = "http://localhost/project/index.php/clientapinew/post_login2";

        // JSON data
        JSONObject jsonObject = new JSONObject();
        try{
            jsonObject.put("Email", email);
            jsonObject.put("Password", password);
        } catch (JSONException e){
            e.printStackTrace();
        }

        // Json request
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
                LOGIN_REQUEST_URL,
                jsonObject,
                new Response.Listener<JSONObject>(){
                    @Override
                    public void onResponse(JSONObject response){
                        //Toast.makeText(context, "Product successfully added", Toast.LENGTH_SHORT).show();
                        try{
                            //use the response JSONObject now like this log
                            Log.d(TAG, response.getString("Success"));
                            boolean success = response.getBoolean("Success");
                            if (success) {
                                //...
                            }
                        } catch (JSONException e) {
                            System.out.println("Error logging in");
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                if (error instanceof NetworkError) {
                    Toast.makeText(LoginActivity.this, "Can't connect to Internet. Please check your connection.", Toast.LENGTH_LONG).show();
                }
                else if (error instanceof ServerError) {
                    Toast.makeText(LoginActivity.this, "Unable to login. Either the username or password is incorrect.", Toast.LENGTH_LONG).show();
                }
                else if (error instanceof ParseError) {
                    Toast.makeText(LoginActivity.this, "Parsing error. Please try again.", Toast.LENGTH_LONG).show();
                }
                else if (error instanceof NoConnectionError) {
                    Toast.makeText(LoginActivity.this, "Can't connect to internet. Please check your connection.", Toast.LENGTH_LONG).show();
                }
                else if (error instanceof TimeoutError) {
                    Toast.makeText(LoginActivity.this, "Connection timed out. Please check your internet connection.", Toast.LENGTH_LONG).show();
                }

                //Do other stuff if you want
                error.printStackTrace();
            }
        }){

            @Override
            public Map<String,String> getHeaders() throws AuthFailureError {
                Map<String,String> headers = new HashMap<String,String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                return headers;
            }
        };

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
                3600,
                0,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        RequestQueueSingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
    }

And then your onClick should look something like

loginBtn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
          String Email = emailEdt.getText().toString();
          String Password = passwordEdt.getText().toString();
          login(Email, Password);
       }

}

Create RequestQueueSingleton.java class and use something like this:

public class RequestQueueSingleton {

private static RequestQueueSingleton mInstance;
private RequestQueue mRequestQueue;

private static Context mCtx;

private RequestQueueSingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

}

public static synchronized RequestQueueSingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new RequestQueueSingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}
}

Upvotes: 2

Matin Gdz
Matin Gdz

Reputation: 217

The first character in the response is ">". When it tries to run this line:

JSONObject jsonResponse = new JSONObject(response);

It can't find a JsonObject in the response and your code won't work. My suggestion is to remove ">" from your response and try again.

Upvotes: 0

Related Questions