Unable to make jsonarrayrequest with volley - android

Im trying to make a post request with volley.
The request parameter is a json array .
Following is my request parameter
[
"Type",
{
"User": "email",
"password": "dimmer",
}
]
I have a method frameJsonArray that frames the above json and im making post request as follows,
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(Request.Method.POST, Constants.requestUrl, frameJsonArray(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
error.printStackTrace();
}
}
);
Im getting error in the above line of code where im making the request. How can I get this sorted?
Following is my error log
Error:(162, 46) error: constructor JsonArrayRequest in class JsonArrayRequest cannot be applied to given types;
required: String,Listener<JSONArray>,ErrorListener
found: int,String,JSONArray,<anonymous Listener<JSONObject>>,<anonymous ErrorListener>
reason: actual and formal argument lists differ in length
Following is my frameJsonArrayMethod
public JSONArray frameJsonArray() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("login_type", "Android");
jsonObject.put("username", email);
jsonObject.put("password", password);
jsonObject.put("short_name", null);
jsonObject.put("ip","123.421.12.21");
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put("Login");
jsonArray.put(jsonObject);
Log.d(TAG, "he;ll " + jsonArray.toString());
Toast.makeText(getApplicationContext(), jsonArray.toString(), Toast.LENGTH_SHORT).show();
return jsonArray;
}

JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
Source : http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

once check your JSON , wrong format , you missed double quote.
[
"Type",
{
"User": "email /** you missed double quote here **/,
"password": "dimmer",
}
]

JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(Request.Method.POST, Constants.requestUrl, frameJsonArray(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
error.printStackTrace();
}
}
);
Change JSONObject to JSONArray in onResponse()
EDIT The error coming because there is only one constructor in JsonArrayRequest i.e.
public JsonArrayRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener){}
source https://android.googlesource.com/platform/frameworks/volley/+/e7cdf98078bc94a2e430d9edef7e9b01250765ac/src/com/android/volley/toolbox/JsonArrayRequest.java
you are using some constructor with 5 arguments.

Related

JSON Array Parsing using Android Volley without a TAG

How can I parse the following JSON using Android Volley?
[
{
"msg": "success",
"id": "1542",
"firstname": "Sam",
"lastname": "Benegal",
"email": "bs#gmail.com",
"mobile": "8169830000",
"appapikey ": "f82e4deb50fa3e828eea9f96df3bb531"
}
]
That looks like pretty standard JSON, so Volley's JsonObjectRequest and JsonArrayRequest request types should parse it for you. For example:
JsonArrayRequest request = new JsonArrayRequest(
Request.Method.GET,
"https://yoururl",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONArray response) {
JSONObject msg1 = response.getJSONObject(0);
String firstName = msg.getString("firstname") // Sam
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO
}
}
);
Code example adapted from the documentation, here: https://developer.android.com/training/volley/request#request-json.
try this
StringRequest stringRequest = new StringRequest(URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray1 = new JSONArray(response);
for (int i = 0; i < jsonArray1.length(); i++) {
JSONObject object = jsonArray1.getJSONObject(i);
{
Toast.makeText(this, ""+object.getString("msg")+"\n"+object.getString("id"), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);

Volley JsonObjectRequest Error response

I've got class with simple Json Object Request, this is method where whole request is called, and in LogCat I get only:
Volley: [2] 2.onErrorResponse: Error:
so I don't know where to look for a fix
private void getBeerDetails() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET,
"https://api.punkapi.com/v2/beers/13",
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
beerName.setText(response.getString("name"));
alc.setText(response.getString("abv"));
ibu.setText(response.getString("ibu"));
firstBrewed.setText(response.getString("first_brewed"));
yeast.setText(response.getString("yeast"));
description.setText(response.getString("description"));
foodPairing.setText(response.getString("food_pairing"));
Picasso.with(getApplicationContext())
.load(response.getString("image_url"))
.into(beerImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error:", error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
}
As I see here your response is in JsonArray format.
So try with below
private void getBeerDetails() {
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest
(Request.Method.GET,
"https://api.punkapi.com/v2/beers/13",
null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if(response.length()>0){
//make a loop and add item to your list
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error:", error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
}
Your error message is not very descriptive. However, I think you need to set the content-type to application/json in the header for your GET request. Override the getHeaders function while creating the request. Here's a java example.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
Update
As per your comment in the answer, you have failed to parse the JSON which was returned from your GET request. As I have seen from your response JSON, you are receiving an array of objects. I would like to suggest using Gson for JSON parsing. Its simple and easier to implement. You need to define a class containing the fields of the object in your array which is returned in your response. Then just use Gson to convert the values from JSON array into the array of that specific object that you have created. Here's a sample.
Gson gson = new Gson();
Data[] dataArray = gson.fromJson(jsonLine, Data[].class);

Volley What Request Type to use for the format

I'm New to android Volley. I accessing a API server and its response is JSON.
The response JSON is like this\
{
status:true,
data : [{
id:1,
name:'name 1',
},
{
id:2,
name:'name 2 ',
}]
}
I tried using JsonObjectRequest & JsonArrayRequest in Volley. Both throws error. What is the Right request type to use and How to parse it?
You will need to use a JsonObjectRequest for this, if it is a post request use the following
try{
JSONObject jsonBody = new JSONObject("add json body to post");
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(LookUp.url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// pDialog.cancel();
try{
if(response.getString("status").equals("true")){
JSONArray jsonArray=response.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name=jsonObject.getString("name");
}
}
}
catch (JSONException error){
Log.e("TAGJE", error.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAGE", error.getMessage(), error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
return params;
}
};
mQueue.add(jsonObjectRequest);
}
catch (JSONException ex){
ex.printStackTrace();
}
and for a get request follow this
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try{
if(response.getString("status").equals("true")){
JSONArray jsonArray=response.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name=jsonObject.getString("name");
}
}
}
catch (JSONException error){
Log.e("TAGJE", error.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});

Why am I getting NullPointerException error in this Volley onResponse?

In my app I am posting the user's phone number and getting a JSON Array as response, of the form [{"category" : "category", "name" : "name", "phone" : "phone", "comment" : "comment"}, etc etc ..... ]
I am trying to format this JSON Array response in my ListView but I am getting this error and my app shuts down. Help would be appreciated.
java.lang.NullPointerException
at appname.onResponse(ListView.java:130)
at appname.onResponse(ListView.java:83)
Below is my code :
StringRequest stringRequest = new StringRequest(Request.Method.POST, SelectUserReviews_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(ListView.this, response, Toast.LENGTH_LONG).show();
JsonArrayRequest movieReq = new JsonArrayRequest(SelectUserReviews_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Review review = new Review();
review.setCategory(obj.getString("category"));
review.setName(obj.getString("name"));
review.setPhone(obj.getString("phone"));
review.setComment(obj.getString("comment"));
reviewList.add(review);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error geting user info: " + error.getMessage());
hidePDialog();
}
});
// Adding request for getting user info to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error getting user: " + error.getMessage());
hidePDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_PHONENUMBER_USER, phoneNoofUser);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Line 130 is :
AppController.getInstance().addToRequestQueue(movieReq);
Line 83 is :
new Response.Listener<String>() {

com.android.volley.ParseError: org.json.JSONException

I got this error from volley library
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
the error
com.android.volley.ParseError: org.json.JSONException: Value [{"id":"admin","name":"Admin"}] of type org.json.JSONArray cannot be converted to JSONObject
How can I receive the result as string and then I will process it using jackson ?
If you want to receive the result as a string don't use the JSONRequest. Go with the simple Request class.
Your problem is pretty simple the server is giving back a JSONArray with just one element inside.
A JSONArray is not a JSONObject. That's why the parsing is failing.
We Have to use JsonArrayRequest instead of JsonObjectRequest. The code as:
RequestQueue queue = Volley.newRequestQueue(this);
final String url = "http://192.168.88.253/mybazar/get_product_list.php";
// prepare the Request
JsonArrayRequest getRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
// add it to the RequestQueue
queue.add(getRequest);
Hope, it's solve the problem.
I noticed that there is class JsonArrayRequest supported by volley so I use this class and the problem solved, I was using JsonObjectRequest
https://android.googlesource.com/platform/frameworks/volley/+/43950676303ff68b23a8b469d6a534ccd1e08cfc/src/com/android/volley/toolbox
Probably the below logic will work for you:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject1 = new JSONObject(response.toString());
JSONArray jsonArray = jsonObject1.getJSONArray("statewise");
Log.d("Json response", "onResponse: "+jsonObject1.toString());
for (int i = 0; i < jsonArray.length; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//Here you will get your result so can use textview
//to populate the result
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: "+error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}

Categories

Resources