This question already has answers here:
How do you use the Android Volley API?
(8 answers)
Closed 5 years ago.
My json Data
{"code":1200,"message":"Data Retrieved","data":[{"id":1,"name":"Vangipurapu Venkata Sai Laxman","skills":"Cricketer, Batsman","image":"https:\/\/qph.ec.quoracdn.net\/main-qimg-4f5029c4319b41270f5643d461979645-c"},{"id":2,"name":"Himesh Reshammiya","skills":"music director, singer, producer, lyricist, distributor and actor","image":"https:\/\/starsunfolded-1ygkv60km.netdna-ssl.com\/wp-content\/uploads\/2016\/01\/Himesh-Reshammiya-nasal-singing.jpg"},{"id":3,"name":"Rajkummar Rao","skills":"Indian actor","image":"https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn:ANd9GcQhShfz5g33MOXBKtLlEXo16uuxEpHFL8NYQE2lg071avavYeKr"},{"id":4,"name":"Pusarla Venkata Sindhu","skills":"badminton player","image":"https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn:ANd9GcTC0wYTxk72MNx5IADgDDMAqUz9AEyfR6UZexWNqn_fKFNZCLz-"}]}
This is my Mainactivity
MainActivity.java
JsonArrayRequest rqst = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
DataSet dataSet = new DataSet();
dataSet.setName(obj.getString("name"));
dataSet.setImage(obj.getString("image"));
dataSet.setSkills(obj.getString("skills"));
list.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
What changes Should i Made to fetch the data? I should fetch that data in to an listview.
you are expecting a JSONArray but your response is a JSON object that contains a JSON array.
modofy your request to a StringRequest
StringRequest strtRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
JSONObject obj = new JSONObject(response);
JSONArray arr=obj.getJSONArray("data");
for(int i=0;i<arr.length();i++){
JSONObject jo=arr.getJSONObject(i);
DataSet dataSet = new DataSet();
dataSet.setName(jo.getString("name"));
dataSet.setImage(jo.getString("image"));
dataSet.setSkills(jo.getString("skills"));
list.add(dataSet);
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) ;
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());
}
});
This question already has answers here:
how to parse JSONArray in android
(3 answers)
Closed 4 years ago.
I have a JSOn array without array name and I'm confused how to parse it and how to make JSONObject or JSONArray. If possible then please describe it.
My JSON Array list is:
[{
name:"Product_fill",
image:"https://something.com/product1.jpg",
title:"Laptop 1"
},
{
name:"Product_fill2",
image:"https://something.com/product2.jpg",
title:"Laptop 2"
},
and my code is :
RequestQueue queue= Volley.newRequestQueue(this);
String Url="http://msomething.com/list.php";
StringRequest request=new StringRequest(Request.Method.GET, Url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//weatherData.setText("Response is :- ");
parseData(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("Data Not Received");
}
});
queue.add(request);
super.onStart();
}
private void parseData(String response) {
try {
// Create JSOn Object
JSONObject jsonObject=new JSONObject(response);
JSONObject main=jsonObject.getJSONObject("array");
JSONArray jsonArray=jsonObject.getJSONArray("0");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1=jsonArray.getJSONObject(i);
textView.setText(jsonObject1.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this:
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <jsonArray.length() ; i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
textView.setText(jsonObject.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
You can pass the response string to the JSONArray constructor directly and then parse the array using a loop
JSONArray jsonArray = new JSONArray(response);
Tip: I would search how to use other json libraries like Gson or Jackson as the Android built-in parser is not good.
json with int key value
I've been stuck, to call json like this to android studio using volley, I've never done this before
According to this json with int key value
you are
receiving jsonArray instead of jsonObject
so you have to
send the request of JsonArray with volley
then the request will return jsonArray then you can get your string like this.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest("url", new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response)
{
try
{
for (int i=0;i<response.length();i++)
{
JSONArray jsonArray = response.getJSONArray(i);
for (int j=0;j<jsonArray.length();j++)
{
String yourString = jsonArray.getString(j);
// you can convert it into int as per your requirement
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError 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 need to retrieve a list of json objects from mysql database, parse it using volley and populate a listview with it. I'm new to php and volley. Here's how I'm trying.
JSON:
{"result":[{"id":"3133482000","name":"John Doe","class":"3A","parent":"admin#gmail.com","status":"0","stopid":"6","busno":"0"},{"id":"0","name":"","class":"","parent":"","status":"0","stopid":"0","busno":"0"},{"id":"334","name":"sam","class":"3a","parent":"","status":"0","stopid":"2","busno":"0"}]}
Android:
JSONArray sts;
public static final String STUDENT_URL = "http://www.smartlbus.esy.es/getAllStudents.php";
students=new ArrayList<Student>();
StringRequest stringRequest = new StringRequest(STUDENT_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=null;
jsonObject = new JSONObject(response);
sts = jsonObject.getJSONArray(JSON_ARRAY);
for (int i = 0; i < sts.length(); i++) {
JSONObject jo = sts.getJSONObject(i);
Student s=new Student();
Toast.makeText(StudentDetails.this,jo.getString(STUDENT_NAME),Toast.LENGTH_SHORT).show();
s.setId(jo.getString(STUDENT_ID));
s.setName(jo.getString(STUDENT_NAME));
s.setClassNo(jo.getString(STUDENT_CLASS));
s.setBusno(jo.getString(STUDENT_BUS));
s.setStatus(Integer.parseInt(jo.getString(STUDENT_STATUS)));
s.setStopid(jo.getString(STUDENT_STOP));
students.add(s);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
listView.setAdapter(new CustomListAdapter(StudentDetails.this,students));
Please help me out. In case this doesn't meet the standards here, please comment and let me know. I'll take it down.
Try to use Gson to ease your development.
Create your Java POJO Class:
public class StudentList {
List<Student> results;
// setter
public static class Student {
String name;
String id;
String status;
String class;
String stopid;
String busno;
// getter
}
}
Then parse them using GSON in the onResponse() method.
I'd suggest to use Retrofit to make network calls.
Gson gson = new Gson();
StudentList list = gson.fromJson(response);
// populate to ListView using list.getResults()
Try this & also check your URL. Your url not returning any json response.
StringRequest stringRequest = new StringRequest(Request.Method.GET,STUDENT_URL ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.d("TAG","response :"+response);
JSONObject jsonObject = new JSONObject(response);
sts = jsonObject.getJSONArray(JSON_ARRAY);
for (int i = 0; i < sts.length(); i++) {
JSONObject jo = sts.getJSONObject(i);
Student s=new Student();
Log.d("TAG","Name :"+jo.getString(STUDENT_NAME));
// Toast.makeText(StudentDetails.this,jo.getString(STUDENT_NAME),Toast.LENGTH_SHORT).show();
s.setId(jo.getString(STUDENT_ID));
s.setName(jo.getString(STUDENT_NAME));
s.setClassNo(jo.getString(STUDENT_CLASS));
s.setBusno(jo.getString(STUDENT_BUS));
s.setStatus(Integer.parseInt(jo.getString(STUDENT_STATUS)));
s.setStopid(jo.getString(STUDENT_STOP));
students.add(s);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
e.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);