JSON Array Request Parsing error using Volley Library - android

I'm working on a news application with api from newsapi.org. I'm using volley library for making JSONArrayRequest and getting data. I'm trying to get my head around json array and json object to understand the parsing. Unfortunately, I'm unable to parse the response. It always calls OnErrorResponse where the response is the json data. Can someone guide me how can I parse the response?
Response:
URL to site:
https://newsapi.org/docs/endpoints/sources
Parsing:
public void jsoncall() {
JsonArrayRequest arrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject;
Log.d("OnResponse", "" + response);
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
JSONArray jsonArray = jsonObject.getJSONArray("sources");
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Toast.makeText(getActivity(), "" + jsonObject1.getString("name"), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this,anime.toString(),Toast.LENGTH_SHORT).show();
lstAnime.add(anime);*/
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getActivity(), "Size of Liste " + String.valueOf(lstAnime.size()), Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), lstAnime.get(1).toString(), Toast.LENGTH_SHORT).show();
setRvadapter(lstAnime);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("OnErrorResponse",""+error.toString());
}
});
requestQueue = Volley.newRequestQueue(Objects.requireNonNull(getActivity()));
requestQueue.add(arrayRequest);
}

dear you are receiving JSONObject include "status" and "sources". I suggest to call JsonObjectRequest
Then parse your response to get JSONArray "sources" :response.getJSONArray("sources");

Related

Not able to fetch JSON data [using volley Library] in Android

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

org.json.JSONException in volley

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.

Parsing an array from Flask to Android

I am trying to parse an array that I have retrieved from my flask server. The array is as follows.
"[{\"firstName\": \"Roy\", \"lastName\": \"Augustine\"}]"
I am parsing the array in Android studio using the following code.
private void loadDrives() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://142.93.216.24:5000/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
//adding the product to product list
driveList.add(new TestMl(
jsonObject.getString("firstName"),
jsonObject.getString("lastName")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
I am however getting the following error.
org.json.JSONException: Value [{"firstName": "Roy", "lastName": "Augustine"}] of type java.lang.String cannot be converted to JSONObject
The error suggests that the json is being successfully retrieved, but it cannot parse the array successfully. Could anybody suggest a suitable solution?
YOu're fetch data using wrong name.. it is lastName not lastname
Change this
driveList.add(new TestMl(
array.getString("firstname"),
array.getString("lastname")
));
To
driveList.add(new TestMl(
array.getString("firstName"),
array.getString("lastName")
));

get object integer json to android studio

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

How can I parse a JSON request using Volley?

I am using the Volley Facebook library to parse the JSON object by passing the String Parameter. But it's throwing JSON exception.
[
{
"error":false,
"newsletter":[
{
"title":"IPS Informa",
"date":"2015-12-02",
"posted_by":"admin",
"image":"1449324052220174144.png",
"description":"Hello World",
"id":"4",
"post_count":"0"
},
{
"title":"IPS Informa",
"date":"2015-11-30",
"posted_by":"admin",
"image":"1449324052220174144.png",
"description":"Hello Worl Two",
"id":"1",
"post_count":"6"
}
]
}
]
And here is My Android Code to parse my JSON request:
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hidePDialog();
try {
JSONObject first = new JSONObject(response);
String err = first.getString("error");
JSONArray second = first.getJSONArray("newsletter");
fisco_tips.clear();
// Parsing json
for (int i = 0; i < second.length(); i++) {
JSONObject obj = second.getJSONObject(i);
FisoTipsSinglton fisco_obj = new FisoTipsSinglton();
//Set Newsletter ID
fisco_obj.setFisco_id(obj.getString("id"));
//Set Title
fisco_obj.setTitle(obj.getString("title"));
//Set Posted Date
fisco_obj.setPosted_date(obj.getString("date"));
//Set Posted By
fisco_obj.setPosted_by(obj.getString("posted_by"));
//Set Image URL
fisco_obj.setThumbnailUrl(obj.getString("image"));
//Set Short Description
fisco_obj.setShort_description(obj.getString("description"));
fisco_obj.setPost_count(obj.getString("post_count"));
fisco_tips.add(fisco_obj);
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("Json Error", "Here is error: " + e.toString());
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidePDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("country", country);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, related_posts);
}
How can I read my JSON object using string request in Android Volley library?
The error message that you're getting:
type org.json.JSONArray cannot be converted to JSONObject
indicates that you're trying to convert a JSONArray to a JSONObject. This happens in the first line of code in your try block.
JSONObject first = new JSONObject(response);
You're passing the entire response to the JSONObject constructor, but the response is wrapped in [ ], so it's a JSONArray, not a JSONObject. Your first step should be to parse the response as a JSONArray, get the JSONObject from the first element of the array, then continue parsing.
try {
JSONArray wrapper = new JSONArray(response);
JSONObject first = (JSONObject)wrapper.get(0);
boolean err = first.getBoolean("error");
JSONArray newsletters = first.getJSONArray("newsletter");
// Parsing json
for (int i = 0; i < newsletters.length(); i++) {
JSONObject news = newsletters.getJSONObject(i);
.
.
.
}
} catch (JSONException e) {
Log.d("MainActivity.java", e.toString());
}
If there's a chance that your data source might return an empty array, you should do more error checking than I've shown here.
String err = first.getString("error");
Should be:
Boolean err = first.getBoolean("error");
Plus what Bill the Lizard said.
Instead of using Volley check OkHTTP with Retrofit. It will wrap responses automatically ;)

Categories

Resources