I first time try to parse json with volley. i found some examples and i learned how to use it.
but I have one problem....
i have like this json
{
"Items ":
[
{
"Branch" :"mybranch",
"City" : "London"
},
{
"Branch" :"mybranch1",
"City" : "Paris"
},
{
"Branch" :"mybranch2",
"City" : "NY"
}
]
}
and this is a my parser code
private void makeGetDictionaries13Request() {
showpDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
urlgetbranchlist, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("TAG", response.toString());
try {
JSONArray mainjsonArray=response.getJSONArray("");
for (int i = 0; i < mainjsonArray.length(); i++) {
JSONObject j_object=mainjsonArray.getJSONObject(i);
System.out.println();
Log.e("City", j_object.getString("City"));
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
I can show jsonobject result in log but i have volley error
no value for
for my option i have something wrong in parse son..what am i doing wrong?
There is a minor mistake in getting JSONArray from the JSONObject response. You actually forgot to mention the array name which is items.
Mistake:
JSONArray mainjsonArray=response.getJSONArray("");
Correct:
JSONArray mainjsonArray=response.getJSONArray("Items");
Use Items instead of "" for getting Items JSONArray from response JSONObject:
JSONArray mainjsonArray=response.getJSONArray("Items");
Related
The jason array request code goes like this:
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET,url, (JSONArray) null , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.d("Response:", String.valueOf(response.getJSONObject(0)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response not recieved", Toast.LENGTH_SHORT).show();
}
});
And I've used a singleton instance of a request queue, to fetch the data,
AppController.getInstance(context.getApplicationContext()).addToRequestQueue(arrayRequest);
I'm using an api service that supplies a bunch of questions (The api generates a url, which returns a collection of JSON Objects, An Array (Just try and Open the url link, the json array will be seen)
But when I run the app, the request is not even getting a response,the progam flow is going into the error listner block.
Can someone explain this behaviour? Is it because the JSON array supplied by the url, has nested arrays? Why?
I tried reading and anlyzing other questions here, which might have the same issue, But i found nothing.
You want to just change JsonArrayRequest to JsonObjectRequest:
Please copy and paste below code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String category = jsonObject.getString("category");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
// hide the progress dialog
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, "TAG");
Follow this link for learn other request: Androidhive
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've sent parameter to my server but in return it sent error message,
JSONObject cannot be converted to JSONArray
this is my code:
// Creating volley request obj
JsonObjectRequest taxiReq = new JsonObjectRequest (url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray taxiJsonArray = response.getJSONArray("taxi_list");
// Parsing json
for (int i = 0; i < taxiJsonArray.length(); i++) {
JSONObject obj = taxiJsonArray.getJSONObject(i);
Taxi taxi = new Taxi();
taxi.setTaxiname(taxiJsonArray.getString("taxiname"));
taxi.setThumbnailUrl(taxiJsonArray.getString("image"));
taxi.setdeparture(taxiJsonArray.getString("departure"));
taxi.setarrive(taxiJsonArray.getString("arrive"));
taxi.setseat(taxiJsonArray.getInt("seat"));
taxi.setcost(taxiJsonArray.getInt("cost"));
// adding taxi to taxi array
taxiList.add(taxi);
}
} 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) {
Log.e(TAG, "Requesting Taxi Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
})
and this is my json:
{
"error": false,
"taxi_list": [
{
"image": "http://localhost/androidapp/taxiprofile/1.jpg",
"taxiname": "Taxi 1",
"from": "PTK",
"to": "SGU",
"departure": "08:00:00",
"arrive": "13:00:00",
"seat": 7,
"cost": 12
},
{
"image": "http://localhost/androidapp/taxiprofile/default.jpg",
"taxiname": "Taxi 2",
"from": "PTK",
"to": "SGU",
"departure": "08:00:00",
"arrive": "13:00:00",
"seat": 2,
"cost": 15
},
{
"image": "http://localhost/androidapp/taxiprofile/2.jpg",
"taxiname": "Taxi Untung Selalu",
"from": "PTK",
"to": "SGU",
"departure": "09:00:00",
"arrive": "14:00:00",
"seat": 3,
"cost": 13
}
]
}
I've tried to change JSONObject to JSONArray but it still come with errors...
maybe because I tried to get object but there isn't one...
EDIT: new error, after I changed the code
error: incompatible types: String cannot be converted to int
in line:
taxi.setTaxiname(obj.getString("taxiname"));
any help?
you have to change your Volley request to JsonObjectRequest. So your code will be:
// Creating volley request obj
JsonObjectRequest taxiReq = new JsonObjectRequest (url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
JSONArray taxiJsonArray = response.getJSONArray("taxi_list");
// Parsing json
for (int i = 0; i < taxiJsonArray .length(); i++) {
try {
JSONObject obj = taxiJsonArray.getJSONObject(i);
Taxi taxi = new Taxi();
taxi.setTaxiname(obj.getString("taxiname"));
taxi.setThumbnailUrl(obj.getString("image"));
taxi.setdeparture(obj.getString("departure"));
taxi.setarrive(obj.getString("arrive"));
taxi.setseat(obj.getInt("seat"));
taxi.setcost(obj.getInt("cost"));
// adding taxi to taxi array
taxiList.add(taxi);
} 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) {
Log.e(TAG, "Requesting Taxi Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
})
Your "JSONArray response" is not a JsonArray It is a JsonObject try this once
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
JSONArray responceArray = response.getJSONArray();
// Parsing json
for (int i = 0; i < responceArray.length(); i++) {
------------- Your code------------
}
}
You're expecting for a JSONArray, but your top level element is actually an object:
{ <--- This is a JSON Object
"error": false,
"taxi_list": [
{
"image": "http://localhost/androidapp/taxiprofile/1.jpg",
"taxiname": "Taxi 1",
"from": "PTK",
"to": "SGU",
"departure": "08:00:00",
"arrive": "13:00:00",
"seat": 7,
"cost": 12
},
You need to change this:
JsonArrayRequest taxiReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>()
To request a JsonObject instead.
Make StringRequest instead of JSONObjectRequest and use this method it will work fine.
Problems in your code:
you were taking values directly from array and not from jsonobject.
you were not checking for the response came from the server is correctly formatted in JSON or not. StringRequest will help you on that matter.
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Log.d(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(s);
if (jsonObject.getString("error").equals("false")) {
JSONArray taxiJsonArray = jsonObject.getJSONArray("taxi_list");
// Parsing json
for (int i = 0; i < taxiJsonArray.length(); i++) {
JSONObject obj = taxiJsonArray.getJSONObject(i);
Taxi taxi = new Taxi();
taxi.setTaxiname(obj.getString("taxiname"));
taxi.setThumbnailUrl(obj.getString("image"));
taxi.setdeparture(obj.getString("departure"));
taxi.setarrive(obj.getString("arrive"));
taxi.setseat(obj.getInt("seat"));
taxi.setcost(obj.getInt("cost"));
// adding taxi to taxi array
taxiList.add(taxi);
}
}
} 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 volleyError) {
Log.e(TAG, "Requesting Taxi Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
});
i´d like to create a search for my Android app but when I try to I just get the JSON Value along with ...JSON Object cannot be converted to JSONArray. Btw I am using Volley.
Code Sample for getting JSON:
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, R.string.i_enter_request, Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,getString(R.string.d_wait),getString(R.string.d_fetch),false,false);
String url = AppConfig.DATA_URL+editTextId.getText().toString().trim();
JsonArrayRequest searchReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
Toast.makeText(getApplicationContext(), "Response: " + response.toString(), Toast.LENGTH_LONG).show();
loading.dismiss();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject pObj = response.getJSONObject(i);
Products item = new Products();
item.setTitle(pObj.getString("name"));
ProductItems.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
loading.dismiss();
}
});
AppController.getInstance().addToRequestQueue(searchReq);
}
And the JSON itself by searching for "1":
{
products: [
{
id: "1",
name: "Test",
price: "123",
item_desc: "Its a Test"
}],
success: 1
}
It would be great if someone could help me with it.
Thanks
This is not a JSONArray:
{products:[{id: "1", name: "Test", price: "123", item_desc: "Its a Test" } ], success: 1 }
So you're getting an error because your callback tries passing it in as a JSONArray You need to change your callback to:
#Override
public void onResponse(JSONObject response) {}
And then you need to parse the response as a JSONObject, not a JSONArray.
My volley throw error response when trying to parse JSON data inside listview. Is is because of my JSON data in object node, not array node.
JSON data
{
"users": [{
"userId": 1,
"name": "Dya Vega",
"profilePhoto": "https://graph.facebook.com/1301454197/picture?type=large",
"dateMatched": "1/1/2015",
"distance": "1 miles away",
"status": "Online",
"requestMessage": "Hi, can I know you?",
"like": 234,
"lastActive": "Active 1 hour ago"
}, {
"userId": 2,
"name": "Esa Ezzatinor",
"profilePhoto": "https://graph.facebook.com/1269334432/picture?type=large",
"dateMatched": "1/1/2015",
"distance": "2 miles away",
"status": "Online",
"requestMessage": "Hi, can I know you?",
"like": 234,
"lastActive": "Active 2 hour ago"
}]
}
Code
// Creating volley request obj
JsonArrayRequest userReq = new JsonArrayRequest(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);
User user = new User();
user.setName(obj.getString("name"));
user.setProfilePhotoUrl(obj.getString("profilePicture"));
user.setLastActive(obj.getString("lastLogin"));
// adding movie to movies array
userList.add(user);
} 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: " + error.getMessage());
hidePDialog();
}
});
Note:
=> if string contains { first character then string contain JSONObject as root container
=> if string contains [ first character then string contain JSONArray as root container
Posted json string contain JSONObject as root instead of JSONArray. use JsonObjectRequest instead of JsonArrayRequest for making request to server using Volley
You have users objects in an array inside an object. So you would want to start with a new JsonObjectRequest.
Edited: With the below code, you retrieve JSONObject type response, inside you have a JSONArray type users, after that you can loop through the JSONArray and retrieve each JSONObject from it.
JsonObjectRequest req = new JsonObjectRequest(URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray users = response.getJSONArray("users");
for (int i = 0; i < users.length(); i++) {
try {
JSONObject obj = users.getJSONObject(i);
User user = new User();
user.setName(obj.getString("name"));
user.setProfilePhotoUrl(obj.getString("profilePicture"));
user.setLastActive(obj.getString("lastLogin"));
// adding movie to movies array
userList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
MainActivity onErrorResponse
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setId(obj.getString(TAG_ID));
item.setNama(obj.getString(TAG_NAMA));
item.setAlamat(obj.getString(TAG_ALAMAT));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});