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);
}
});
Related
Below is the response what i am getting i want to get the data from "SourceJson" m not ble to understnd why i am getting "" in source json please help me
{
"incomingOrder": [
{
"Namw": 8510,
"Surname": "00",
"mob": "00",
"phone": "000",
"SourceJson": "{\"cart_gst\":30.21,\"instructions\":\"\",\"order_packing_charges\":30,\"cart_igst_percent\":0,\"cart_sgst\":15.1038,}",
"test": "NotSynced",
"test": "DPA",
}]}
Try this code :
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("incomingOrder");
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject objSourceJson=jsonObject.getJSONObject("SourceJson");
Log.i("IvaSourceJson",objSourceJson.toString());
String cart_gst=objSourceJson.getString("cart_gst");
String instructions=objSourceJson.getString("instructions");
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
As it is JSONArray data is of list type, better not to use jsonArray.getJSONObject(0);.
Use this code for multiple results,
StringRequest request = new StringRequest(Request.Method.GET, "", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("incomingOrder");
for (int i = 0; i < array.length(); i++){
JSONObject object1 = array.getJSONObject(i);
String name = object1.getString("Namw");
String surname = object1.getString("Surname");
String mob = object1.getString("mob");
String phone = object1.getString("phone");
String sourceJson = object1.getString("SourceJson");
String test = object1.getString("test");
String test1 = object1.getString("test");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
});
Context context;
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
Code this in any method and call the method where the action needed.
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);
}
I am building a app to upload images to my company server.
The issue I have run into I have to make 2 spinners one to select an upload category and another to select a client, I am in testing phase with this now, the problem is my Spinner doesnt populate with the JSON data at all the json data is stored in a ASP file if that matters
I have only been coding for about 2 weeks so any help would be aprecieted.
Json data
{ "success": 1, "Name": [ { "Country": "India" }, { "Country": "US" }, { "Country": "UK" }, { "Country": "Australia" }, { "Country": "Canada " } ] }
MainActivity
public class MainActivity extends AppCompatActivity {
Spinner spinner;
String URL="https://www.smartpractice.co.za/app-categories.asp";
ArrayList<String> CountryName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CountryName=new ArrayList<>();
spinner=(Spinner)findViewById(R.id.country_Name);
loadSpinnerData(URL);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String country= spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),country,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// DO Nothing here
}
});
}
private void loadSpinnerData(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.getInt("success")==1){
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String country=jsonObject1.getString("Country");
CountryName.add(country);
}
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, CountryName));
}catch (JSONException e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
Currently it's looks like you not correctly parse your JSON to object.
And you can see it if you add breakpoint on your catch e.printStackTrace(); and debug.
My advice is to use Gson to parse data to object (so you will have lower chances to have a mistake).
See reference: https://medium.com/#ankit.sinhal/parsing-json-with-gson-library-184d94a04dec
I also advice to use Retrofit for network requests https://medium.com/#prakash_pun/retrofit-a-simple-android-tutorial-48437e4e5a23
JSONObject jsonObject = new JSONObject(response); is the Mistake (casting error)
because in your response ClientID, Username and Pwd all are a string so it gives Error. and as you write in try-catch method your app is not crashing.
=> You just to do String array = response.substring(47); before giveing response to JSONObject. (so it removes all above value and start from your array which have values)
=> and after that replace response to array. It will work definitely.
Example:-
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, "onResponse: " + response);
String array = response.substring(47);
Log.i(TAG, "onResponse: array " + array);
try {
JSONObject jsonObject = new JSONObject(array);
Log.i(TAG, "onResponse: success :- " + jsonObject.getInt("success"));
if (jsonObject.getInt("success") == 1) {
Log.i(TAG, "onResponse: Name :- " + jsonObject.getJSONArray("Name"));
JSONArray jsonArray = jsonObject.getJSONArray("Name");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Log.i(TAG, "onResponse: Country :- " + jsonObject1.getString("Country"));
String country = jsonObject1.getString("Country");
CountryName.add(country);
}
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, CountryName));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Replace above request in you request
On the below code i want to use Response but it throws JSONException
StringRequest strReq = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v(TAG, "Response: " + response);//output {"error":false}
try {
JSONObject jo = new JSONObject(response); // java.lang.String cannot be converted to JSONObject
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Sample JSON string:
{
"error": false,
"uid": "5b081af13eb974.69226352",
"user": {
"name": "66699",
"created_at": "2018-05-25 18:47:21"
}
}
How i should solve this?
Well, to retrieve the content of your response you don't need to use JSON while using POST request. Instead do something like this :
if (response.equalsIgnoreCase("yourResponseFromTheWebService")) {
...
Toast
} else if (response.equalsIgnoreCase("OtherPossibleResponse")){
....
Toast
} else{
....
Toast
}
in case of GET request you should do something like this :
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// display response
try {
//put response into string
JSONArray Jresult = response.getJSONArray("user");
for (int i = 0; i < Jresult.length(); i++) {
JSONObject json_data = Jresult.getJSONObject(i);
String lName = json_data.getString("name");
String lCreatedAt = json_data.getString("created_at");
//create a model class with your user info like name and created_at and for every user found create a new user object and store its info.
_myUser.add(new User(lName, lCreatedAt));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(getRequest);
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();
}
});