Getting JSONArray result in "org.json.JSONException: Value{data}" - android

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());
}
});

Related

Not able to fetch JSON data from api of covid19india for my android app using Volley

I want to fetch data from this file: https://api.covid19india.org/state_district_wise.json
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"https://api.covid19india.org/state_district_wise.json",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("Jammu and Kashmir");
progressDialog.cancel();
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
// I want get case details of "Jammu and Kashmir"
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
What should I use here:
JSONArray jsonArray = jsonObject.getJSONArray("Jammu and Kashmir");
Data comming from API is JSONArray, not JSONObject
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, "https://api.covid19india.org/v2/state_district_wise.json",null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject dataOBJ = response.getJSONObject(i);
JSONArray jsonChild = dataOBJ.getJSONArray("districtData");
for (int k = 0; k < jsonChild.length(); k++) {
JSONObject obj = jsonChild.getJSONObject(k);
// work to be done...
}
}
} catch (Exception exp) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
The code is working fine now. Read this for complete sollution.

What is the alternative solution if node response not have json array name

My JSON RESULT
This is my JSON output. Here array name not available
[{"item":"WATER"},{"item":"DFG"},{"item":"2InchPipe"},{"item":"5InchPipe"}]
Android Code
But I want to display the item in the android spinner. I was used volley method for getting all item from JSON.
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String getitem=
try{
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("*What to do here*");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String country=jsonObject1.getString("Item");
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);
I have doubt in this line
JSONArray jsonArray=jsonObject.getJSONArray("*What to do here*");
Finally i got a solution using following code
JsonArrayRequest requestQueue = 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);
String country = obj.getString("item");
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) {
}
});
}
MySingleton.getmInstance(MainActivity.this).addToRequestQue(requestQueue );
You can direct pass you output in Array:
JSONArray jsonArray=new JSONArray (response);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String country=jsonObject1.getString("Item");
CountryName.add(country);
}

Convert Json object to an array

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);

How to combine the two request in which one give response for another api key which pass for request

I want to parse two api at the same time in which one api get a response of key that key has api link and pass in another StringRequest forget response.
This is my function for parsing in which I want to parse firstly one api and get a response in response href name of key use for another api parse link.
please help me as soon as.
I searched and I got this link but it is not proper code.
https://www.versti.eu/TranslateProxy/https/stackoverflow.com/questions/37584001/how-to-combine-the-two-request-url-from-json-to-get-output-in-volley
private void parseSmartPhone()
{
StringRequest stringRequest= new
StringRequest(com.android.volley.Request.Method.GET,
Config.HOMECTEGORY, new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onResponse(String response) {
try {
//getting the whole json Array from the response
// JSONObject jsonObject= new JSONObject(response);
JSONArray jsonArray = new JSONArray(response);
mylist=new ArrayList<>();
for (int i = 0;i<=2;i++)
{
latestsphone= new LatestSmartPhoneModel();
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject objtitle=jsonObject.getJSONObject("title");
title=objtitle.getString("rendered");
objtitle=jsonObject.getJSONObject("_links");
JSONArray imgJsonArray=objtitle.getJSONArray("wp:featuredmedia");
JSONObject objJsonImg=imgJsonArray.getJSONObject(0);
StringRequest request1= new StringRequest(com.android.volley.Request.Method.GET,objJsonImg.getString("href"), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject= new JSONObject(response);
JSONObject imggild=jsonObject.getJSONObject("guid");
String rendered=imggild.getString("rendered");
latestsphone.setLink(rendered);
latestsphone.setTitle(title);
mylist.add(latestsphone);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
requestQueue.add(request1);
request1.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
UpcomingAdapter imgAdapter=new UpcomingAdapter(getActivity(),mylist);
recyclerUpcoming.setAdapter(imgAdapter);
recyclerUpcoming.setLayoutManager(new GridLayoutManager(getActivity(),2));
recyclerUpcoming.setHasFixedSize(true);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
This is your proper code, i corrected your posted code, Use these as global parameter.
ArrayList<LatestSmartPhoneModel> mylist = new ArrayList<>();
String title,link;
private void parseSmartPhone() {
final RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, Config.HOMECTEGORY, new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onResponse(String response) {
try {
//getting the whole json Array from the response
// JSONObject jsonObject= new JSONObject(response);
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= 3; i++) {
if (i==3)
{
i=4;
}
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject objtitle = jsonObject.getJSONObject("title");
title = objtitle.getString("rendered");
link=jsonObject.getString("link");
objtitle = jsonObject.getJSONObject("_links");
final LatestSmartPhoneModel latestsphone = new LatestSmartPhoneModel();
latestsphone.setTitle(title);
latestsphone.setLink(link);
JSONArray imgJsonArray = objtitle.getJSONArray("wp:featuredmedia");
JSONObject objJsonImg = imgJsonArray.getJSONObject(0);
StringRequest request1 = new StringRequest(com.android.volley.Request.Method.GET, objJsonImg.getString("href"), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject imggild = jsonObject.getJSONObject("guid");
String rendered = imggild.getString("rendered");
latestsphone.set_links(rendered);
mylist.add(latestsphone);
UpcomingAdapter imgAdapter = new UpcomingAdapter(getActivity(), mylist);
recyclerUpcoming.setAdapter(imgAdapter);
recyclerUpcoming.setLayoutManager(new GridLayoutManager(getActivity(), 2));
recyclerUpcoming.setHasFixedSize(true);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request1);
request1.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}

How to retrieve a JSON without name using Volley on Android?

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);

Categories

Resources