Search code examples
javaandroidjsonpostandroid-volley

Use input data in jSon body volley post request


I'm new to android programming and JSON. I'm trying to call a authentication API with volley post request. I'm trying get the the username and password inserted from the user and sending to the API and returning the response. It seems I can't directly pass the input into JSON body of the request. Can you point a way to input the data getting from the user input to JSON body request. I'm attaching my code, so you can get a better idea. Thanks.

public class LoginActivity extends AppCompatActivity  {

    Button login_btn;
    EditText input_username, input_password;
    String url;
    RequestQueue queue;
    StringRequest stringRequest;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        login_btn = findViewById(R.id.btn_login);
        input_username=findViewById(R.id.editText_username);
        input_password=findViewById(R.id.editText_password);
        
        url="https://restful-booker.herokuapp.com/auth";
        try {
            queue=Volley.newRequestQueue(this);
            JSONObject jsonBody = new JSONObject();


            String username = input_username.getText().toString();
            String password = input_password.getText().toString();


            jsonBody.put("username", username);
            jsonBody.put("password", password);

            final String mRequestBody = jsonBody.toString();
            stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(LoginActivity.this, response,Toast.LENGTH_LONG).show();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                   Toast.makeText(LoginActivity.this, error.toString(),Toast.LENGTH_LONG).show();
                }
            }){

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap header= new HashMap();
                    header.put ("accept","*/*");
                    header.put ("Content-Type","application/json");
                    return  header;
                }
                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8";
                }
                @Override
                public byte[] getBody() throws AuthFailureError {
                    try {
                        return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException uee) {
                        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                        return null;
                    }
                }
                //Return Response code
            };
            login_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    queue.add(stringRequest);
                }
            });

        }
        catch (JSONException e) {
            e.printStackTrace();
        }


    }
}

Solution

  • I think that you are getting text of edittext directly onCreate instead of onClick

    This will work

    public class LoginActivity extends AppCompatActivity {
    
        Button login_btn;
        EditText input_username, input_password;
        String url;
        RequestQueue queue;
        StringRequest stringRequest;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
    
            login_btn = findViewById(R.id.btn_login);
            input_username=findViewById(R.id.editText_username);
            input_password=findViewById(R.id.editText_password);
    
            url="https://restful-booker.herokuapp.com/auth";
            queue=Volley.newRequestQueue(this);
    
            login_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String username = input_username.getText().toString();
                    String password = input_password.getText().toString();
    
                    try {
                        JSONObject jsonBody = new JSONObject();
                        jsonBody.put("username", username);
                        jsonBody.put("password", password);
    
                        final String mRequestBody = jsonBody.toString();
                        stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Toast.makeText(LoginActivity.this, response,Toast.LENGTH_LONG).show();
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                               Toast.makeText(LoginActivity.this, error.toString(),Toast.LENGTH_LONG).show();
                            }
                        }){
    
                            @Override
                            public Map<String, String> getHeaders() throws AuthFailureError {
                                HashMap header= new HashMap();
                                header.put ("accept","*/*");
                                header.put ("Content-Type","application/json");
                                return  header;
                            }
                            @Override
                            public String getBodyContentType() {
                                return "application/json; charset=utf-8";
                            }
                            @Override
                            public byte[] getBody() throws AuthFailureError {
                                try {
                                    return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                                } catch (UnsupportedEncodingException uee) {
                                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                                    return null;
                                }
                            }
                        };
    
                        queue.add(stringRequest);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    

    Hope It Works!!