Volley: unable to set break point for onResponse method - android

I am using Volley Library to make network calls and I am using it for the first time. I am trying to set a break point in onResponse method but the break point is getting toggled on JsonObjectRequest. Following is my code
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, urlL1, "", new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(CVLenderApp.TAG, response.toString());
// I would like to set the break point at this line
Toast.makeText(SignInActivity.this, "Success", 3000).show();
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(CVLenderApp.TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userName", "name");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
// Adding request to request queue
CVLenderApp.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
I hope I'm doing a small mistake, but I'm unable to figure that out.
Thank you,
Anudeep Reddy.

As I commented, for POST request's parameters, override getBody instead of getParams
Moreover, if your project uses Google's official Volley, then try the following sample code:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userName", "name");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
});
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps!

Related

How to send json data with header using volley library

I am trying to send json data to a url in the format below.
{
“amount”:500,
“merchant_id”:”104”,
“narrative”:”John”,
“reference”:”Steven”
}
To send data to the url, one needs an authorization key as the header, I have already figured out how to set the authorization key as the header in Params, as shown below
#Override
public Map<String,String >getHeaders()throws AuthFailureError{
Map<String,String >params=new HashMap<String,String>();
params.put(“Content-Type”, “text/jsom;);
params.put(“AuthKey”, Auth);
return params;
but I do not know how to send the data in the particular format shown in the first instance to the url using params with volley. Please help, I am quite new to using Volley library .
This is the rest of code I am currently using it however does not return any response except for an invalid json error. Meaning the format sent is not corresponding to the one desired.
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(Main9Activity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main9Activity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("amount","500");
params.put("merchant_id", "104");
params.put("narrative","John");
params.put("reference", "Steven");
return params;
}
#Override public Map<String,String>getHeaders()throws AuthFailureError{
Map<String,String>headers=new HashMap<>();
params.put("Content-Type","text/json");
params.put("Authorization",Auth);
return params;
}
};
RequestQueue requestQueue=Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
You can refer below code snipet to post data with custom header in volley.
JSONObject jsonobject = new JSONObject();
jsonobject.put("amount", "500");
jsonobject.put("merchant_id", "104");
jsonobject.put("narrative", "John");
jsonobject.put("reference", "Steven");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, jsonobject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
Toast.makeText(Main9Activity.this, response.toString(), Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(Main9Activity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String >headers=new HashMap<String,String>();
headers.put(“Content-Type”, “application/json“);
headers.put(“AuthKey”, Auth);
return headers;
}
You can send as below:
The data you want to send:
Hashmap<String, Object> data = new HashMap<>();
data.put("amount", "500");
data.put("merchant_id", "104");
data.put("narrative", "John");
data.put("reference", "Steven");
RequestQueue request = Volley.newRequestQueue(context);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, "your url",new JSONObject(data),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
){
};
request.add(jsonobj);

Adding parameters on Restful API using JsonObjectRequest on Android Studio

I'm calling a restful api on my android project and I used Volley and JsonObjectRequest, I thought that the third parameter of the JsonObjectRequest which is jsonRequest are the api parameters so I created a json object for that which in the end I only got errors. So is it common to directly add the api parameters on the url? instead of passing it on a json object? what is the third parameter for, it would be really helpful if someone can give me an example. And my last question is how do you get the entire json response instead of using response.getString("title") for each key.
//api parameters directly added on the url
String URL = "https://www.myapi.com/?param=sample&param1=sample1";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String title = response.getString("Title");
Log.d("title", title);
} catch(Exception e){
Log.e("response error", e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}
});
Below your Response.ErrorListener() you need to add these two overrides:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("param", "sample");
params.put("param1", "sample1);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
return headers;
}
};

Android volley post methode parameter missing

I am using android volley library to post data to back-end service. But I can't send any parameter with my request. I have done each and everything mentioned here . But none works for me. The post method that I am using is:
public static void post()
{
// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
String url = "http://myUrl";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Always the response is "parameter missing".
How could i resolve this issue?
If you're using JSONObjectRequest, you can try this.
String url = "http://myurl";
Map<String, String> params = new HashMap<String, String>();
params.put("key", value);
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
success = jsonObject.getInt("success");
message = jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Activity activity = getActivity();
if (volleyError instanceof NoConnectionError) {
String errormsg = "Check your internet connection";
Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
}
}
});
queue.add(jsonObjectRequest);
The codes are more likely the same as yours. Check on the lines where I put the data to be posted. I'm very sure this would work!
The problem is you are approaching the request as though you were making a stringRequest. The link you reference is talking specifically about making a stringRequest.
jsonObjectRequest actually lets you put the json object into the constructor itself, instead of using the override method getParams() like so:
String url = "some_url";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(Constants.LOGIN_EMAIL_ID, email);
jsonObject.put(Constants.LOGIN_PASSWORD, password);
}catch(JSONException e){
Log.d("JSON error", e.getMessage(), e);
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error.getMessage()!=null){
Log.d("RESPONSE", error.getMessage());
}
}
});
VolleySingleton.getInstance(activity).getRequestQueue().add(jsObjRequest);

Post JsonObject with Volley

I'm trying to send a Post request with volley without success.
The lib is working correctly, and I manage to sent some string requests, but the Post with a JsonObject doesn't work.
String urlJsonReq = "https://api.parse.com/1/classes/GameScore";
String tag_json_obj = "tag_json";
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
urlJsonReq,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("MyApp", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("MyApp", "Error: " + error.getMessage());
// hide the progress dialog
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("value1", "testValue1");
params.put("value2", "testValue2");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-Parse-REST-API-Key", "xxxxxxxxxxxx");
headers.put("X-Parse-Application-Id", "xxxxxxxxxxx");
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
I keep getting an error. I read somewhere, but without any details that the volley cannot sent JsonObjects, only receive then. That if you want to solve that problem you should implement an custom class, but I really don't know if I'm just making an stupid mistake here (it is possible).
Do you guys know something about that?
Thank you for your time.
You can send the JSONObject without overiding the getParams or getBodyContentType. Something like this for example
JSONObject object = new JSONObject();
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, url, object, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Obviously you can Override the headers if you need to.

how to send json object to server using volley in android

I want to send the JSONObject to server using POST method . I have used volley library to pass the string params its working fine, but if i try to use json object its showing an error for calling the json object here is my code
private void makeJsonObjReq() {
showProgressDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("un", "xyz#gmail.com");
params.put("p", "somepasswordhere");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,tag_json_obj);
// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}
And my Error form server is : [10031] BasicNetwork.performRequest: Unexpected response code 401
How to solve this problem. I want to add application/json;charset=utf-8 in header please check my code whether its correct or not . Please give me a suggestion to over come this problem
Third parameter in JsonObjectRequest is for passing post parameters in jsonobject form. And for header you need to send two separate values one for content-type one for charset.
RequestQueue queue = Volley.newRequestQueue(this);
private void makeJsonObjReq() {
showProgressDialog();
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("un", "xyz#gmail.com");
postParam.put("p", "somepasswordhere");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setTag(TAG);
// Adding request to request queue
queue.add(jsonObjReq);
// Cancelling request
/* if (queue!= null) {
queue.cancelAll(TAG);
} */
}
Create new Method and call it in OnClick method
public void PostOperation() {
requestQueue = Volley.newRequestQueue(this);
pdialog = new ProgressDialog(this);
pdialog.setMessage("Loading");
pdialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, "YOUR_URL",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pdialog.dismiss();
Log.e("login output", response);
//MODEL CLASS
LoginModel loginModel = new GsonBuilder().create().fromJson(response, LoginModel.class);
if (loginModel.getStatus().toString().equalsIgnoreCase("true")) {
Intent i = new Intent(context, DashboardActivity.class);
startActivity(i);
finish();
Toast.makeText(context, loginModel.getStatus() + "", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, loginModel.getMsg() + "", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pdialog.dismiss();
Toast.makeText(getApplicationContext(), "Invalid Credentials", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> map = new HashMap<String, String>();
// pass your input text
map.put("email" editTextEmail.getText().toString());
map.put("password",editTextPassword.getText().toString() );
map.put("uid", "1");
map.put("type", "login");
Log.e("para", map + "");
return map;
}
};
requestQueue.add(stringRequest);
}

Categories

Resources