I am writing a simple JSONArrayRequest. This is my JSONArrayRequest:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
I'm confused on why we set the jsonRequest parameter in JsonArrayRequest to null. The only docs I found was this: https://developer.android.com/training/volley/request, which didn't really explain much. If somebody could explain this, I would really appreciate it. Thank you.
As the documentation says, the parameters of JsonArrayRequest are:
method - the HTTP method to use
url - URL to fetch the JSON from
jsonRequest - A JSONArray to post with the request. Null indicates no parameters will be posted along with request
listener - Listener to receive the JSON response
errorListener - Error listener, or null to ignore errors
So the null value you're passing is for the parameters to post along with the request, which can be null if you have nothing to pass.
jsonRequest as the name suggests json in request means something as payload you want to pass onto the server.
GET: is the type of HTTP method used for getting some info from the server and in that case we usually don't have to pass any payload to the server hence the jsonRequest is null in that case means the body will be empty in your API request.
POST/PUT: is the type of HTTP method used for creating/updating info on the server and in that case we have to pass any payload to server hence the jsonRequest is non-null in that case means the body will be the json data which we will pass as jsonRequest in your API request.
Update:
jsonRequest is of type JSONArray in JsonArrayRequest, so you can just convert your arraylist into jsonarray and pass it on.
ArrayList<String> list = new ArrayList<String>();
list.add("hello");
list.add("CodingChap");
JSONArray jsonArray = new JSONArray(list);
Related
I want to send parameters such as username and password.
I got an error like String cannot be converted to jsonobject.
I dont know what this happening.Anyone pls help me my code is:
JSONObject obj=new JSONObject();
try{
obj.put("username","test");
obj.put("password","test");
} catch (JSONException e) {
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
urlJsonObj, obj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,json_obj_req);
}
There is nothing wrong with the way you are creating JSONObject and putting values in it. Make sure the response received is Json, because your onResponse method accepts JSONObject. You could be receiving String value as response, which could not be converted to JSONObject.
It looks like your response is actually a string and not a json object i.e. {"object":"value"} but rather "object:value". You need to sniff your response via either Stetho, Fiddler or reenact your request via Postman (or Fiddler)
======================
This doesn't answer your question, but this will help you tremendously and make your life easier.
Highly recommend using Gson and Retrofit to make HTTP requests and parse Gson objects easily.
https://github.com/google/gson
http://square.github.io/retrofit/
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, null,
new Response.Listener<JSONObject>() {
Does the above code send JSON Object to a particular URL?
Ok, the JSONObject class from Volley, normally has two conditions:
the third param is the json you want to send.
If you use:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, null,
new Response.Listener<JSONObject>() {
}
.
.
.
You you are using the first constructor, that means you want to send some object in your body request, and if you send null, volley in the constructor do this param.toString(), so if you send null, imagine, null.toString(), obviously will crash, that is not possible operation of a null object.
So the other option is to use the second constructor:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN,
new Response.Listener<JSONObject>() {
}
.
.
.
You dont have to send the third param (the param/json body), so this constructor auatomatically has the condition that you dont want to send nothing to the server. I think you have to use the second constructor, otherwise could fail.
Regards.
I want to get the count of the documents in remote mongodb database. For that I am using custom query url. The url only returns an integer instead of a JSON packet. I am using Volley in android to make this query. The following code gives Error: E/Error﹕ com.android.volley.ParseError: org.json.JSONException: Value 2 of type java.lang.Integer cannot be converted to JSONObject
JsonObjectRequest request = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d("onResponse", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Error",volleyError.toString() );
}
});
The request made using the url in a browser gives the following result.
It's not a JSON Request Use String request so it will return the response as a 2.
so simple you can get this using
int value = yourjsonobject.getInt("key");
If it helps please let me know
I am doing an update on the old project & I don't have much knowledge of Android as of now. In project we have Comments section on product.
For comment after sending earlier we had return as 0 (some error) & 1 (success).
Below is the code we were using.
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Method.POST,
act.getString(R.string.CommentForUserURL),
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(
JSONObject response) {
Log.d("response done", "done===" + response);
mloading.setVisibility(View.GONE);
if (response != null) {
Comment obj = new Comment();
JSONObject jsonObject = response;
try {
obj.setComment(jsonObject
.getString("Comment"));
Now we have changed the return object from 0/1 to user object.
Does this need need to update JsonObjectRequest to GJSON request? Or object will also get parsed with JsonObjectRequest?
I am asking because when I execute above, I get error as below.
01-25 12:30:21.754: E/Volley(16487): [10114] BasicNetwork.performRequest:
Unexpected response code 500 for
http://new.souqalharim.com/add/CommentForMerchant
Any idea why I am getting this error?
Note: This URL is working fine for iPhone application.
Edit 1
This is post method, so full url is not there. There are few more parameters to add like ?comment=MyComment&userId=123&productId=234. As it is post I am not adding parameters in actual url.
I have those in another methods
#Override
protected Map<String, String> getParams()
throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("productId", productId.toString());
params.put("userId",
mSessionManager.getUserCode().toString());
params.put("comment", GlobalFunctions
.EncodeParameter(med_comments
.getText().toString()));
return params;
}
Full url is as below.
http://new.souqalharim.com/add/CommentForUser?productId=325&userId=5&comment=abcd
I tested this in Mozilla RESTClient and it works fine.
Edit 2
After checking further I found protected Map<String, String> getParams() throws AuthFailureError { is not getting called. Any idea why this is happening?
The problem is below.
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Method.POST,
act.getString(R.string.CommentForUserURL),
null, new Response.Listener<JSONObject>() {
^^^^
It should be
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Method.POST,
act.getString(R.string.CommentForUserURL),
new JSONObject(params), new Response.Listener<JSONObject>() {
^^^^^^^^^^^^^^^^^^^^^^
Copy code from protected Map<String, String> getParams() before final JsonObjectRequest.
That's it!!!
Reason is as below.
The JsonObjectRequest is extended JsonRequest which override getBody() method directly, so your getParam() would never invoke, I recommend you extend StringRequest instead of JsonObjectRequest.
your can check this answer for more details.
Actually 500 means Internal server error and this is caused by the Rest-api you are calling and not due to Volley,so check the back-end code.
BasicNetwork.performRequest: Unexpected response code 500
The server receives the correct response, but detects an error, this error is due to the PHP connection file with the database, this code must have the function implemented to hide the values of the query to avoid sql insertion
use this sample code:
<?php
$con = new mysqli('localhost', 'u648230499_wololo', '*********', 'u648230899_ejexample');
if ($con->connect_error) {
echo 'error connect database: ', $con->connect_error;
exit();
}
$participantId = $_POST['participantId'];
$name = $_POST['name'];
$sql = $con->prepare('INSERT INTO participant VALUES (?,?)');
$sql->bind_param('is', $participantId, $name);
$sql->execute();
echo 'OK\n';
$con->close();
?>
I'm trying to send a JSON as string (not as object) to the server (in this case it's a WebAPI). I always get a error code 500.
I succeeded to get response from the server when the request was GET and without sending data to the server. this achieved by JsonObjectRequest.
Now, I trying to send a POST request with JSON as string. For that I try
JsonObjectRequest
StringRequest
GsonRequest
JsonRequest - here I supplied my json in the requestBody
Before using volley, I used other methods to send request to server which require to simply build an object, serialized to json (string) and pass via StringEntity.
I can't understand where should I pass the json in the request. or what I'm doing wrong.
I don't exactly understand why do you want to send the JSON as a string and not as an object. Nevertheless, in your WebAPI endpoint you should put a breakpoint in the Post method of the ApiController and see whether the request gets there or not.
Probably, you're mixing the content-types of the request. If you want to send a simple string request from Volley, you should just use the StringRequest and send there the JSON text. Thus, in the WebAPI POST method you must get the string without being deserialized to JSON. I answered once a similar question of how this string request should be made here.
However, as I said before I would suggest using always JSON requests which includes the contentType:"application/json" header, and receive requests in the WebAPI deserialized.
url = "yoururl"; StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
} ) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("your_field", youJSONObject.toString());
return params;
} }; queue.add(postRequest);
Try in this way to make the post (it should work with json obj or array)