So i am a beginner in android programming. I have run into a problem . I am trying to get JSON data from a fake API . But due to some problem in my request i cant get the data in my response . I tried debugging with breakpoints but the loop (which adds the received data to the arraylist) is not getting executed . Can anyone pls tell me what the error in my code is ?
the API link is :- https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json
public class Repository {
RequestQueue queue;
ArrayList<Question> questionArrayList = new ArrayList<>();
String url = "https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
public ArrayList<Question> getQuestions(final SyncInterface callback){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
Question question = new Question(response.getJSONArray(i).get(0).toString(),
response.getJSONArray(i).getBoolean(1));
//Add questions to arraylist/list
questionArrayList.add(question);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (callback != null)
callback.isFinished(questionArrayList);
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Tag","error");
}
});
queue = AppController.getInstance().getRequestQueue();
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
return questionArrayList;
}
}
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 have a simple URL that fetches some pics from pixabay website. with this URL: https://pixabay.com/api/?key=15507399-305bf88eb0892f7cdf58fb66b&image_type=photo&pretty=true&q=yellow+flowers.
Clicking on the link it is shown the JSON response. I want to get the "id" and "largeImageURL". but the method doesn't even execute. the Arraylist that is supposed to contain the values is always size = 0.
I have added the
<uses-permission android:name="android.permission.INTERNET"/>
I have no clue what I'm missing here
requestQueue = Volley.newRequestQueue(this);
loadImages();
//testing
String[] names = null;
for (int i = 0; i < images.size(); i++) {
names[i] = images.get(i).getId();
}
}
private void loadImages() {
String url = "https://pixabay.com/api/?key=15507399-305bf88eb0892f7cdf58fb66b&image_type=photo&pretty=true&q=yellow+flowers";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray hits = response.getJSONArray("hits");
for (int i = 0; i < hits.length(); i++) {
JSONObject pics = hits.getJSONObject(i);
images.add(new Flowers(pics.getString("id"), pics.getString("largeImageURL")));
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "ha", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("test", "Error", error);
}
});
requestQueue.add(request);
}
Your code is working except that the placement of the block of codes '//testing' is at the wrong location resulting in size = 0. It takes time for the data to come in before 'onResponse()' get triggered and stores the data in 'images'. But you are already accessing the 'images' before 'onResponse()'.
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
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"));
}
}
Hello friends I have following JSON Array response from a web service and I want to read all the data row wise from the Database and display on Android Activity.
[{"id":"2","type":"0","title":"Recruitment at ADANI Port, Mundra","date":"2016-07-01"},{"id":"1","type":"1","title":"Training at DAICT, Gandhinager","date":"2016-07-04"}]
I have implemented following code in onCreate() of an Activity using Volley Library, which doesn't show output and to my knowledge it doesn't call onResponse() method.
public void getNews(){
String url = "http://www.ABCDXYZ.net/tponews.php?tponews=1";
Log.e("URL",url);
requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jor = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.e("Resposne", "We have got the response");
JSONObject val = response.getJSONObject(0);
}catch (JSONException e){e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley",error.toString());
}
}
);
requestQueue.add(jor);
}
The output is only URL in Log.e("URL",url); // URL: www.ABCXYZ.net/tponews.php?tponews=1