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();
}
});
Related
Good Day,
I am having a problem fetching my JSON file using Android Studio. How can I call a specific JSONObject for example on my code below I want to know if the inputted phone number is equals to the JSONObject number. I am trying to read the JSONArray and store in individually on different strings.
Every time I am trying to call obj.getString("phonenum") inside the loop the only value I am getting is the last value.
My code are as follow.
JSON File.
GetInfo.php
[
{
"id": 1,
"name": "Angelo Dayao",
"email": "angelo#gmail.com",
"phonenum": "639201234567"
},
{
"id": 2,
"name": "Angelo Dayao",
"email": "angelogg#g.com",
"phonenum": "639161234567"
},
{
"id": 3,
"name": "Anna Chelzia",
"email": "anna#g.com",
"phonenum": "639771234567"
}
]
JAVA FILE Code
public void GetData(){
StringRequest stringRequest = new StringRequest(Request.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++){
try {
JSONObject obj = null;
obj = jsonArray.getJSONObject(i);
if(obj.getString("phonenum") == phonenumber){
Toast.makeText(getApplicationContext(), obj.getString("phonenum"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
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);
This question already has answers here:
How to send a POST request with JSON body using Volley?
(3 answers)
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I am using volley to post json data to server.The data is in this form.
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"user": {
"first_name": "abc",
"last_name": "xyz",
"username": "abc#gmail.com",
"email": "abc#gmail.com",
"groups": [],
"is_active": true
},
"phone": "1234567890",
"address": "address"
}
]
}
How to post this data using Volley ?
jsonObject is your object that you want to pass
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("count",ObjectList.size());
jsonObject.put("next","");
jsonObject.put("previous","");
JSONArray jsonArray=new JSONArray();
JSONObject jsonObjectUser=new JSONObject();
jsonObjectUser.put("first_name",first_name);
jsonObjectUser.put("last_name",last_name);
jsonObjectUser.put("username",username);
jsonObjectUser.put("email",email);
JSONObject jsonObject1=new JSONObject();
jsonObject1.put("user",jsonObjectUser);
jsonObject1.put("address",address);
jsonObject1.put("phone",phone);
jsonArray.put(jsonObject1);
jsonObject.put("results",jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest request_json = new JsonObjectRequest(URL, new jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//Process os success response
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(request_json);
Please check my below answers which helps you to solved your problem:
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "abc");
jsonObject.put("email", "abc#gmail.com");
JSONArray array=new JSONArray();
for(int i=0;i<your_data.size();i++){
JSONObject obj=new JSONObject();
try {
obj.put("filterId",filter_items.get(i));
obj.put("typeName","CAT_ID");
} catch (JSONException e) {
e.printStackTrace();
}
array.put(obj);
}
And finally add json array as below
jsonObject.put("filter",array);
JsonObjectRequest request_json = new JsonObjectRequest(URL, new jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//Process os success response
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(request_json);
Please check above and put your data into as a key and value, I am using my data as a request parameter.
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);
}
});