How to send object and get array response in volley android? - android

I need to send object value like
{
"Fromdate":"04/11/2018",
"Todate":"11/11/2018",
"Task":"abc"
}
I get response in array
[{}]
Please help for me
Thanks for advance.

If you could edit your question with a bit more explanation about your problem that would be great for me to help you. But I may know what you need.
Volley waits for a JsonRequest to be queued, but you can actually manage it the way you want, if the response from the server is an JsonArray and you want to send a JsonObject, you may want an approach as follows.
You have to extend JsonRequest and work over the response:
private class CustomJsonArrayRequest extends JsonRequest<JSONArray> {
public CustomJsonArrayRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
Then you can setup your request:
JSONObject json = new JSONObject();
try {
json.put("Fromdate", "04/11/2018");
json.put("Todate", "11/11/2018");
json.put("Task", "abc");
} catch( JSONException e){
Log.e("ErrorBuildingJson", "Error building request JSONObject");
e.printStackTrace();
json = null; //GC this
}
//checkConnection is a custom method
if (json != null && checkConnection()) {
// Instantiate the RequestQueue
RequestQueue queue = Volley.newRequestQueue(this);
// Request a string response from the provided URL.
CustomJsonArrayRequest jsonRequest = new CustomJsonArrayRequest(Request.Method.POST, myURI, json,
new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
if (response != null && response.length() > 0) { //If the response is valid
// Do Stuff
} else { //If the response is not valid, the request also failed
Log.e("ErrorOnRequest", "The server responded correctly, but with an empty array!");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ErrorOnResponse", "Response from the server contains errors!");
}
}
);
// Add the request to the RequestQueue.
queue.add(jsonRequest);
}
Notice that this approach expects your server to wait for an simple json object and to return an json array as response.
This is a very common approach, and can be found in many repositories, since it gives you control over the request itself.
Sample: https://github.com/stefankorun/najdisme/blob/master/src/mk/korun/najdismestuvanje/net/CustomJsonArrayRequest.java
I hope this helps you.

Related

Get the header value from the android volley [duplicate]

This question already has answers here:
Getting headers from a response in volley
(2 answers)
Closed 6 years ago.
Can someone please guide me that how to get the header value from the url. I have referred to many tutorials but i could not find any tutorial to get the header value from json. Any help would be highly appreciated.
Here is my code:
JsonArrayRequest obreq = new JsonArrayRequest(Request.Method.GET, JsonURL,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONArray>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONArray response) {
pbHeaderProgress.setVisibility(View.GONE);
try {
// Retrieves the string labeled "colorName" and "description" from
//the response JSON Object
//and converts them into javascript objects
for (int i = 0; i < response.length(); i++) {
JSONObject jresponse = response.getJSONObject(i);
String id = jresponse.getString("id");
Id.add(id);
String auth = jresponse.getString("DJ_author_name");
Author.add(auth);
String date = jresponse.getString("date_gmt");
SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
java.util.Date date4 = null;
try {
date4 = form.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
Date.add(newDateStr);
JSONObject title = jresponse.getJSONObject("title");
String tit = title.getString("rendered");
Title.add(tit);
JSONObject img = jresponse.getJSONObject("better_featured_image");
String pic = img.getString("source_url");
Image.add(pic);
}
// Adds strings from object to the "data" string
linear.setVisibility(RelativeLayout.VISIBLE);
// Adds the data string to the TextView "results"
adapter.notifyDataSetChanged();
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
pbHeaderProgress.setVisibility(View.GONE);
Toast.makeText(Home.this, "error!!! =)",
Toast.LENGTH_SHORT).show();
noi.setVisibility(RelativeLayout.VISIBLE);
Log.e("Volley", "Error");
}
}
);
obreq.setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
You can subclass Request (or any of its subclasses) and override the parseNetworkResponse method:
#Override
protected Response<Bitmap> parseNetworkResponse(NetworkResponse response)
{
Map<String, String> responseHeaders = response.headers;
}
with reference to this stackoverflow's link
please check djodjos answer here
if you mean you want to get the header values of the json that is returned itself, not the headers of the request itself you can use Gson library it's fast reliable and very easy to use
------- Ok then as djodjos answer
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
JSONObject jsonResponse = new JSONObject(jsonString);
jsonResponse.put("headers", new JSONObject(response.headers));
return Response.success(jsonResponse,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
} }
you need to override parseNetworkResponse when you create the new JsonArrayRequest (obreq )
for example
StringRequest request=new StringRequest(GET,"url",listener,errorListener){
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String totalPages=responseHeaders.get("X-WP-TotalPages");
return super.parseNetworkResponse(response);
}
};

pass array data as parameter volley

i have array look like this
arrayname[{"code" : "abc","code2":"cba",}]
i want send it as paramaters,put it in getParam() function with volley to my server
the problem look similiar to this
Volley pass array as parameters
any help how to do it?
thanks in advance
Here is a method in an app I made that does what you're trying to do. (I think?)
My problem was that I had multiple post parameters that I wanted to send, but one of them was an array.
For example:
http://www.yourDB.com/getData.php?param1=blah&param2=blah&param3=[ [array] ].
So... to make sure that the PHP page understands that I'm sending an array, I add data to the array as follows (notice the ' [] ' following the param).
postParams.add(new String[]{"param3[]", itemName});
So... the server sees this:
http://www.yourDB.com/getData.php?param1=blah&param2=blah&param3[]=item1&param3[]=item2&param3[]=item3...
The key to understand is this part:
"#Override
public byte[] getBody() throws AuthFailureError {"
The trick is that you send an ArrayList of String arrays into the method and override the getBody() part like this:
private void Url_2_Adapter(String url, final ArrayList<String[]> postParams) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do something with response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.i(TAG, "WE HAD ERROR " + error.toString());
try {
Toast.makeText(getActivity(), "Server says: Error code " + error.networkResponse.statusCode + "\nIf this continues, please report it! Thanks.", Toast.LENGTH_LONG).show();
}
catch (Exception e){
}
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
StringBuilder result = new StringBuilder();
boolean first = true;
for (String[] entry : postParams)
{
if (first) {
first = false;
} else {
result.append("&");
}
try {
result.append(URLEncoder.encode(entry[0], "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry[1], "UTF-8"));
} catch (UnsupportedEncodingException e) {
// this basically will never happen :)
}
}
return result.toString().getBytes();
}
};
Z_VolleySingleton.getInstance().getRequestQueue().add(stringRequest);
}
For this, you have to make JsonArrayRequest. In Volley there is JsonArrayRequest class use that one for JsonArray request.
This is the method available in JsonArrayRequest class.
public JsonArrayRequest(int method, String url, JSONArray jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
May be this will help you:
JSONArray jArrayInput=new JSONArray();
JSONObject jObjectInput=new JSONObject();
jObjectInput.put("code", abc);
jObjectInput.put("code2", cba);
jArrayInput.put(jObjectInput);
JsonArrayRequest request = new JsonArrayRequest(Method.POST, /*Your base url*/, jArrayInput , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Here success response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Here error response
}
});
MyVolley.getRequestQueue().add(request);
I didn't worked on the Volley Library , I used AsyncHttpClient : The logic you can apply here like this:
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
jsonObject.put("code", abc);
jsonObject.put("code2", cba);
jsonArray.put(jsonObject);// this you need to pass using volley library

Cannot assign value to final Volley variable response

I am familiar with Volley and creating a Singleton class, and adding requests to the queue. However, I wish to increase the modularity of volley and simply call all requests through method call to another class instead. I have setup the present action as basis for the common GET request:
public Object getRequest(String params) {
final JSONObject getRequestReturn = new JSONObject();
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
getRequestReturn = response;
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return getRequestReturn;
}
However, I have a the perplexing catch 22 error on the assignment of response at:
getRequestReturn = response;
The error notes that getRequestReturn must be declared final to allow for use within the inner class, but upon assigning final, another error appears noting that you cannot assign a value to a final variable.
How can this method be handled?
Declare JSONObject as global and initialize in same place like this.
JSONObject getRequestReturn ;
getRequestReturn = new JSONObject();
public Object getRequest(String params) {
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return new JSONObject();
}
U can't get response when u return!Volley request is async!
I use EventBus and I do it like this :
When I need to get data from web , i add a request like this.
Then when i get response from web ,I use EventBus to post a event.
I get the event and update my page.
Or U can try the RxAndroid.

Using custom Volley POST doesn't return anything

I'm trying to use a custom Class that extend the JsonRequest class to send a JSONArrayRequest using POST and a parameter.
public class MethodJsonArrayRequest extends JsonRequest<JSONArray> {
public MethodJsonArrayRequest(int method, String url, JSONObject params, com.android.volley.Response.Listener<org.json.JSONArray> listener, ErrorListener errorListener) {
super(method, url, params.toString(), listener, errorListener);
Log.d("method", Integer.toString(method));
Log.d("jsonRequest", params.toString());
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
My logs return this:
D/method﹕ 1
D/jsonRequest﹕ {"idShow":"219"}
I'm passing this info to my custom class with this snippit:
...
JSONObject params = new JSONObject();
try {
params.put("idShow", idShow);
}
catch (JSONException e) {Log.d("JSON e", e.getMessage()); }
MethodJsonArrayRequest episodeRequest = new MethodJsonArrayRequest(Request.Method.POST, episodeURL, params, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray myResponse) {
try {
Log.d("myResponse", myResponse.toString());
...
Log of myResponse:
D/myResponse﹕ []
But for whatever reason it does not return anything, I feel like I might not be passing the right thing in for the paramas but I'm not sure, any help is greatly appreciated! Let me know if there is something I didn't include here that might be helpful.
user98239820 answer here was extreamly useful. Instead of extending JsonRequest<JSONArray> class he extended the Request class. I also had to change his new JSONObject to new JSONArray to fit my needs, but by pointing to that class works perfectly.

how to get http status code in volley library when response in success.?

I know its a repetitive question, but still. Can any one provide me a solution or workaround to get status code returned with the response when we make a network rest api call?
Here provided a work around. But I didn't understood. Can any one explain me in a better way the solution.?
The rest api returns many success status code like 201,204 and many server errors.
I want to check status code before proceeding and have to make decision accordingly.
This is my existing code.
on a button click
RequestQueue queue;
queue = Volley.newRequestQueue(this);
final String[] token = new String[1];
String status;
String url = "http://myapiurl";
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// want to get status code here
token[0] = response.getString("message");
Toast.makeText(getApplicationContext(),token[0],Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", String.valueOf(error));
}
}
);
queue.add(postRequest);
EDIT: previously didn't answer the question at all.
It seems nontrivial to do this while using the clean Listener interfaces, but it's also possible to implement this as a custom request (the examples specifically show parsing JSON). You can look at the JsonObjectRequest and JsonRequest sources for inspiration.
You should end up with something like this (heavily inspired by JsonObjectRequest):
Request<JSONObject> request = new Request<JSONObject>() {
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
JSONObject obj = new JSONObject(jsonString);
// can access response.statusCode here
// ...
return Response.success(obj, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
};

Categories

Resources