After make a request the volley listener called is onErrorResponse and for my surprise the error message is the callback that I wanted from my server, a json with correct datas.
What is strange thats a parseError but how's a parse error if I make the parse in the onResponse listener.
I'm new in android.
My method:
public void getAllEstablishmentsRequest(){
String url = "http://myServer.com/something";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
try {
JSONObject object = new JSONObject(response.toString());
JSONArray Jarray = object.getJSONArray("data");
for (int i = 0; i < Jarray.length(); i++) {
JSONObject Jasonobject = Jarray.getJSONObject(i);
}
} catch (JSONException e){
Log.e("Volley", "Error JSON");
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Log.e("Volley", "Error - requisição das campanhas de Eutrofização");
System.out.println(error);
}
}
);
requestQueue.add(request);
}
Error: com.android.volley.ParseError: org.json.JSONException: Value {"data":{"establishments":[{"created_by":1,"phone":"(85) 3246-3834","teste":1453583589,"neighborhood":"Joaquim Távora","last_promotion":"2015-10-06 12:42:01","days_last_promotion":110,"id":2,"distance":0,"updated_at":"2015-10-06 12:42:01","address":"Av. Barão de Studart, 2675","name":"São Luiz","updated_by":1,"created_at":"2015-05-31 19:48:58","active":true,"longitude":"-38.510342","latitude":"-3.746922"},{"created_by":3,"phone":"(85) 4008-2444","teste":1453583589,"neighborhood":"Messejana","last_promotion":"2016-01-22 13:45:30","days_last_promotion":2,"id":96,"distance":0,"updated_at":"2016-01-22 13:45:30","address":"Av. Frei Cirilo, 4290","name":"Pinheiro","updated_by":3,"created_at":"2015-12-24 14:27:29","active":true,"longitude":"-38.495841","latitude":"-3.821112"},{"created_by":3,"phone":"","teste":1453583589,"neighborhood":"Vila Peri","last_promotion":"2016-01-21 19:06:16","days_last_promotion":2,"id":140,"distance":0,"updated_at":"2016-01-21 19:06:16","address":"Rua Cônego de Castro, 3859","name":"Cometa","updated_by":null,"created_at":"2016-01-21 18:21:41","active":true,"longitude":"-38.587981","latitude":"-3.800781"}],"establishments_total":134},"success":"YES","time":"2016-01-23 18:13:09"} of type org.json.JSONObject cannot be converted to JSONArray
You are using JsonArrayRequest when you are getting a JsonObject as a response from the server. Use JsonObjectRequest instead. Something like this:
public void getAllEstablishmentsRequest(){
String url = "http://myServer.com/something";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest request = new JsonObjectRequest(url,
new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject object) {
try {
JSONArray Jarray = object.getJSONArray("data");
for (int i = 0; i < Jarray.length(); i++) {
JSONObject Jasonobject = Jarray.getJSONObject(i);
}
} catch (JSONException e){
Log.e("Volley", "Error JSON");
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Log.e("Volley", "Error - requisição das campanhas de Eutrofização");
System.out.println(error);
}
}
);
requestQueue.add(request);
}
Related
I am using Volley to request unsplash API but when I try requesting it as JsonObjectRequest it doesn't give me any errors but I know that is a wrong approach because the data I am receiving is JSONArray
MY APPROACH
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if(response!=null){
// Process the JSON
try{
// Loop through the array elements
for (int i = 0; i < response.length(); i++) {
JSONObject js = response.getJSONObject(i);
Log.d("TESTING",js.getString("id"));
}
p.dismiss();
}catch (JSONException e){
e.printStackTrace();
}
}}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Log.d("TESTING",error.getMessage());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
LOG
Since the JSONArray is too big to post here this is the formate
D/TESTING: org.json.JSONException: Value {"total": 44760,
"total_pages": 4476,
"results":[{JSONObjects}]}
If you wish to view the JSONArray here is the link "https://api.unsplash.com/search/photos?query=wood&client_id=ACESS_KEY_REQUIRED"
also I have viewed this question but that is totally different
You can request a key simply by making an account here.
You need to create jsonObject first. You requested for JSONArray but your server response as JSONObject. Try StringRequest for getting the JSONObject.
Try this:
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
// Loop through the array elements
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject js = jsonArray.getJSONObject(i);
Log.d("TESTING", js.getString("id"));
}
p.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("TESTING",error.getMessage());
}
})
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Hope this will work.
You are request for json object but request time you call jsonarrayrequest so JsonException is come
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject js = jsonArray.getJSONObject(i);
Log.d("TESTING",js.getString("id"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
I am parsing json using volley but its not working and getting error. Follwing is my code and json reponse. please help me to solve this
private void getStaffList() {
showpDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
final String url = "url";
try {
final JSONObject jsonObj = new JSONObject();
jsonObj.put("username", "test");
jsonObj.put("password", "123456");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, jsonObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", "Main response=" + response);
staffarraylist=new ArrayList<DataModel>();;
try {
JSONObject jobSuccess=response.getJSONObject("TABLE_DATA");
Log.d("TAG", "JSONObj response=" + jobSuccess);
JSONArray jarMyData=jobSuccess.getJSONArray("data");
Log.d("TAG", "JSONArray response=" + jarMyData);
for (int i = 0; i < jarMyData.length(); i++) {
JSONArray jar = jarMyData.getJSONArray(i);
DataModel movie = new DataModel();
movie.setName(jar.getString(0));
movie.setOccupation(jar.getString(1));
movie.setPlace(jar.getString(2));
movie.setId(jar.getString(3));
movie.setDate(jar.getString(4));
movie.setPrice(jar.getString(5));
staffarraylist.add(movie);
}
}catch (JSONException e)
{
Log.d("JSONException",e.toString());
}
rcAdapter = new RecyclerViewAdapterHome(MainActivity.this, staffarraylist);
recyclerView.setAdapter(rcAdapter);
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "JSONObj Error: " + error.getMessage());
hidepDialog();
//Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
}
});
requestQueue.add(jsonObjReq);
} catch (JSONException e) {
e.printStackTrace();
}
}
Logcat
Main response={"TABLE_DATA":"{\"data\":[[\"Tiger Nixon\",\"System Architect\",\"Edinburgh\",\"5421\",\"2011/04/25\",\"$320,800\"],[\"Garrett Winters\",\"Accountant\",....so on
D/JSONException: org.json.JSONException: Value {"data":[["Tiger Nixon","System Architect","Edinburgh","5421","2011/04/25","$320,800"],["Garrett Winters","Accountant","Tokyo","8422","2011/07/25","$
First check that your json format is correct or not by clicking here and paste your json for checking. If the response is correct then use Gson. It will parse the response without any error.
I need help in modifying my android studio code for converting Json object to an array. Bellow is the error in my log cat and the actual code.
This is the error message I am getting in the logcat:
04-03 12:01:16.727 19993-19993/com.errandit E/Volley: com.android.volley.ParseError: org.json.JSONException: Value {"data":[{"errand":"Shopping","charges":"500"},{"errand":"House Assistance","charges":"7000"},{"errand":"Pick - Up","charges":"2500"}],"success":1,"message":" 0 records found"} of type org.json.JSONObject cannot be converted to JSONArray
**I am trying to fetch the json array from my wamp server using the method below. **
private void getData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.show();
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Service service = new Service();
service.setName(jsonObject.getString("errand"));
service.setCharges(jsonObject.getInt("charges"));
serviceList.add(service);
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley",error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
Change like below as You are getting JSONObject and inside it there is JSONArray named "data".
JsonObjectRequest jsonObjRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonObj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject mResponse)
{
JSONArray response=mResponse.optJSONArray("data")
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Service service = new Service();
service.setName(jsonObject.getString("errand"));
service.setCharges(jsonObject.getInt("charges"));
serviceList.add(service);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjRequest);
I have a JSON that retrieves all the users of a database. To simplify, I will show the first two users:
[
{
"id":"1",
"name":"Peter",
"age":"25"
},
{
"id":"2",
"name":"Andrew",
"age":"32"
},
...
]
As you can see, it is an array without name that contains some JSONObjects so I have tried to retrieve these data from Android with Volley library going through the whole array but without success.
Here is the code that I have by the moment:
RequestQueue queue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try{
if (response != null) {
for(int i = 0; i < response.length(); i++){
JSONObject obj = response.getJSONObject(i);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG", error.toString());
}
});
queue.add(jsonArrayRequest);
It always gives to me the following error:
Unhandled exception: org.json.JSONException
I also tried to retrieve the JSONArray before trying to retrieve the JSONObject but it does not allowed me because the method
JSONArray json = response.getJSONArray(0);
also gave to me the same error that I have pointed before.
I looked for a lot of examples and I cannot see where my problem is.
What am I doing wrong?
Thanks in advance!
You are not handling JSONException.
Give this a try.
StringRequest request = new StringRequest(Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response)
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Cannot resolve constructor 'JsonArrayRequest(int, java.lang.String, anonymous com.android.volley.Response.Listener<org.json.JSONArray>, anonymous com.android.volley.Response.ErrorListener)'
Error doesn't lie. That request doesn't accept a Method type.
JsonArrayRequest(
String url,
Response.Listener<JSONArray> listener,
Response.ErrorListener errorListener)
StringRequest, on the other hand, does.
StringRequest(
int method,
String url,
Response.Listener<String> listener,
Response.ErrorListener errorListener)
Regarding,
Unhandled exception: org.json.JSONException
response.getJSONObject will throw that exception, so you must use a try-catch.
if (response != null) {
try {
for (int i = 0; ...) {
JSONObject jo = response.getJSONObject(i);
// use 'jo'
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You should add final in final JsonArrayRequest
GOOD LUCK !!
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url,null, new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
try{
if (response != null) {
for(int i = 0; i < response.length(); i++){
JSONObject obj = response.getJSONObject(i);
String tieude = obj.getString("tieudetin");
Toast.makeText(test.this,tieude,Toast.LENGTH_SHORT).show();
//txt.setText(tieude+"");
}
}
}catch(Exception e){
e.getMessage();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(jsonArrayRequest);
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);
}