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
Related
I'm trying to parse json using volley but I cant receive the data. Assume that I received the data. I send that to the recycler view. But I'm not sure about using the JSONObject. Maybe there is a error I couldn't see it. And this is my json website "https://docs.spacexdata.com/#3d6e6f8a-a459-4265-84b1-e2b288a58537".
private void parseJson() {
String url = "https://docs.spacexdata.com/#d65a7f85-e0c7-41ce-b41d-9ad20a238d90";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for(int i = 0; i < response.length(); i++) {
JSONObject capsuleObject = response.getJSONObject(i);
String details = capsuleObject.getString("details");
String type = capsuleObject.getString("type");
mCapsuleList.add(new Capsule("null", "null", "null", "null", 0, 0, type, details, 0));
}
mCapsuleAdapter = new CapsuleAdapter(CapsuleFragment.this.getContext(), mCapsuleList);
mRecyclerView.setAdapter(mCapsuleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
There is a lot of value in json but I just want to receive "type" and "detail". It says my request is null. So how can i parse this?
I am using Volley library to execute my rest APIs.
Using this I have sent email, password entries to URL and receiving response in JSON as:
{
"success": true,
"data": {
"message": false,
"token": "some token value"
}
}
Now I want to parse the 'token' field received from response and do further action. How can this be parsed?
This is the function where I want to parse the response.
public void parseData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("success").equals("true")) {
Toast.makeText(MainActivity.this,"UserExists",Toast.LENGTH_LONG).show();
////RETRIEVE "token" HERE
else {
Toast.makeText(MainActivity.this,"User not registered",Toast.LENGTH_LONG).show();
}
I have seen this link How to parse JSON Object Android Studio but my "token" field is within another object, so not sure how to do it.
if you want to parse JSON in same manual way you have to do like this to get token.
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getBoolean("success")== true) {
Toast.makeText(MainActivity.this, "UserExists", Toast.LENGTH_LONG).show();
JSONObject dataObj= jsonObject.getJSONObject("data");
String token= dataObj.getString("token");
////RETRIEVE "token" HERE
} else {
Toast.makeText(MainActivity.this, "User not registered", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Here is the solution
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject dataObj = response.getObject("data");
String token = dataObj.getString("token");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
}
);
Please use POJO for parsing. Otherwise you will take more time to do this kind of work.
If you are using Volley, why not simply use the JsonObjectRequest:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// parse the response
JSONObject data= response.getObject("data");
String token = data.getString("token");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
}
);
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
You can try like following.
public void parseData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("success").equals("true")){
Toast.makeText(MainActivity.this,"UserExists",Toast.LENGTH_LONG).show();
////RETRIEVE "token" HERE
JSONObject dataObject = jsonObject.getObject("data");
String token = dataObject.getString("token");
}
else {
Toast.makeText(MainActivity.this,"User not registered",Toast.LENGTH_LONG).show();
}
}catch(JSONException e) {
Log.e("YourTAG","exceptions "+e.toString());
}
Hope it helps you.
I Know at first glance it's known mistake made by beginners but:
My standard response looks like this:
public ArrayList<Beer> jsonResponse(){
beerList.clear();
requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
Constants.BASE_API_URL + Constants.BEER_LIST_URL_ENDPOINT,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject beerJsonObject = response.getJSONObject(i);
System.out.println(response.toString());
Beer beer = new Beer();
if (beerJsonObject.has("yeast")) {
beer.setYeast(beerJsonObject.getString("yeast"));
}
beer.setName(beerJsonObject.getString("name"));
beer.setIbu(beerJsonObject.getString("ibu"));
beer.setAlc(beerJsonObject.getString("abv"));
beer.setImgUrl(beerJsonObject.getString("image_url"));
beer.setId(beerJsonObject.getString("id"));
beer.setDescription(beerJsonObject.getString("description"));
beer.setFoodPairing(beerJsonObject.getString("food_pairing"));
beer.setFirstBrewed(beerJsonObject.getString("first_brewed"));
System.out.println(beer.getName()+" "+beer.getIbu()+" "+beer.getImgUrl());
beerList.add(beer);
}
beerRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
return beerList;
}
Everything works except "yeast" item:
if (beerJsonObject.has("yeast")) {
beer.setYeast(beerJsonObject.getString("yeast"));
}
without that if statement I've got standard json err. response no value for "yeast", I thought maybe not every object in response has this value and added that. But that doesn't helped, I still can't get that value, like it wouldn't exist in array, but it's not true, even in System.out.println(response.toString()) I can see a lot of "yeast" .
Here is example response from API I'm working with: https://api.punkapi.com/v2/beers
yeast is under ingredients
so should be:
if (beerJsonObject.has("ingredients")) {
JSONObject ingredients = beerJsonObject.getJSONObject("ingredients");
if (ingredients.has("yeast")) {
beer.setYeast(ingredients.getString("yeast"));
}
}
I am currently using Volley to extract JSON contents using the following code.
JsonArrayRequest servicesStatus = new JsonArrayRequest(url1,
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);
// Having obj to process further
} 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();
}
});
Now, I want one more JSON handler for the new URL and the dialog to be closed once it has successfully downloaded from both the URLs.
I tried to copy paste the above thing with url1 replaced by url2 and different jsonarrayrequest name. And added the hideDialog() in the second one. But the second one is not being called at all.
If you want make multiple request then you will have to add your Request to Queue. You can do it like this:
RequestQueue request = Volley.newRequestQueue(Context);
request.add(FirstRequest);
request.add(SecondRequest);
This should help you to add multiple request in Volley.
I am familiar with Volley and creating a Singleton class, and adding requests to the queue. However, I wish to increase the modularity of volley and simply call all requests through method call to another class instead. I have setup the present action as basis for the common GET request:
public Object getRequest(String params) {
final JSONObject getRequestReturn = new JSONObject();
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
getRequestReturn = response;
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return getRequestReturn;
}
However, I have a the perplexing catch 22 error on the assignment of response at:
getRequestReturn = response;
The error notes that getRequestReturn must be declared final to allow for use within the inner class, but upon assigning final, another error appears noting that you cannot assign a value to a final variable.
How can this method be handled?
Declare JSONObject as global and initialize in same place like this.
JSONObject getRequestReturn ;
getRequestReturn = new JSONObject();
public Object getRequest(String params) {
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return new JSONObject();
}
U can't get response when u return!Volley request is async!
I use EventBus and I do it like this :
When I need to get data from web , i add a request like this.
Then when i get response from web ,I use EventBus to post a event.
I get the event and update my page.
Or U can try the RxAndroid.