joey
joey

Reputation: 83

Volley POST request android

I am not sure i should use which type of content to POST to the api because I am very new to this developing world.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        button = (Button)findViewById(R.id.reg_btn_sign_up);
        btnCancel = (Button)findViewById(R.id.reg_button_cancel);
        Email = (EditText)findViewById(R.id.reg_email);
        Name = (EditText)findViewById(R.id.reg_name);
        Pass = (EditText)findViewById(R.id.reg_pass);
        ConPass = (EditText)findViewById(R.id.reg_confirm_pass);


    button.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            email = Email.getText().toString();
            name = Name.getText().toString();
            password = Pass.getText().toString();
            conPass = ConPass.getText().toString();

            JSONObject jsonBody = new JSONObject();
            try {
                jsonBody.put("username", email);
                jsonBody.put("password", password);
                jsonBody.put("name", name);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            final String mRequestBody = jsonBody.toString();


            StringRequest stringRequest = new StringRequest(Request.Method.POST, reg_url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject = jsonArray.getJSONObject(0);
                        String status = jsonObject.getString("status");
                        String result = jsonObject.getString("result");
                        builder.setTitle("Server Response...");
                        builder.setMessage(result);
                    } catch (JSONException e){
                            e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            })

            {
                @Override
                public byte[] getBody() throws AuthFailureError {

                    try {
                        return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        return null;
                    }

                }


                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8";
                }
            };

            MySingleton.getmInstance(RegisterActivity.this).addRequestQueue(stringRequest);

        }
    });

}

}

This is the log I get in logcat:

W/System.err: org.json.JSONException: Value {"status":0,"result":"Access restricted"} of type org.json.JSONObject cannot be converted to JSONArray

I do it correctly in POSTMAN but I failed to get the result I want in android.

API added in command.

Upvotes: 1

Views: 5364

Answers (4)

primo
primo

Reputation: 1472

try this

  public void login(final String user, final String pass) {
        Log.e("Constant.KEY_URL", String.valueOf(Constant.KEY_URL));
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.KEY_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                     //you will get your response in log
                        Log.e("response", response);

                        if (user.equals("") || pass.equals("")) {

                            Toast.makeText(getApplicationContext(), "username or password is empty", Toast.LENGTH_LONG).show();
                        } else if (!response.equals("empty")) {
                            Log.e("isempty", "yes");

                            try {
                                JSONArray array = new JSONArray(response);
                                for (int i = 0; i < array.length(); i++) {
                                    JSONArray array1 = array.getJSONObject(i).getJSONArray("data");
                                    for (int j = 0; j < array1.length(); j++) {


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

                        } else {
                            Log.e("isempty", "else");
                            Toast.makeText(getApplicationContext(), "Username or password is incorrect", Toast.LENGTH_LONG).show();
                        }


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "username or password is empty", Toast.LENGTH_LONG).show();
                        //  Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
                        Log.e("Error", "msg==>" + error);
                    }
                }) {

            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> reqMap = new LinkedHashMap<>();
                reqMap.put("username", user);
                reqMap.put("password", pass);
                reqMap.put("method", "login");

                Log.e("request","login" + reqMap);

                return reqMap;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 30, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        requestQueue.add(stringRequest);
        stringRequest.setTag("TAG");

    }

call this login method on your button click event

    btnlogin.setOnClickListener(new View.OnClickListener()

    {
        @Override
        public void onClick(View view) {
            user = editusername.getText().toString().trim();
            pass = editpassword.getText().toString().trim();

           login(user, pass);
        }

    });

I'm assuming that you are doing sign up function using volley request response..Relate to my code which i have used for login purpose,you can change it according to your needs..Hope it helps

Upvotes: 4

Dnyaneshwar Panchal
Dnyaneshwar Panchal

Reputation: 444

Use this

JSONObject jsonObject = new JSONObject (response.toString());

Instead of

JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);

Upvotes: 0

AbhayBohra
AbhayBohra

Reputation: 2117

Your are trying to parse an array from your response but you are getting an JSONObject. So first change this line when you get the response

JSONObject jsonObject = new JSONObject(response);

and check the status

if(jsonObject.getString("status").equalsIgnoreCase("0")){
   // show error message or whatever
}else if(jsonObject.getString("status").equalsIgnoreCase("1")){
   // then parse your array if response has it
}

Upvotes: 0

Virat18
Virat18

Reputation: 3505

The response you are getting is JSONObject and not JSONArray

try following code in onResponse method:

try {
                    JSONObject jsonObject = new JSONObject (response);
                    String status = jsonObject.getString("status");
                    String result = jsonObject.getString("result");
                    builder.setTitle("Server Response...");
                    builder.setMessage(result);
                } catch (JSONException e){
                        e.printStackTrace();
                }

Upvotes: 0

Related Questions