Parsing JSON and displaying in a RecyclerView - android

Feedback App
String url = "http://www.dohagarage.com/api/v1/sample";
JsonObjectRequest request = new
JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String naame = hit.getString("question");
mExampleList.add(new ExampleItem(naame));
} mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);mRecyclerView.setAdapter(mExampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
This is the code I used to show the questions using json in a RecyclerView. I want show the options in a radio button.

Please provide more code to better understand but i think you didn't set Layout Manager to RecyclerView

Related

How i can parse in Json Object or Array? Where is error on my code?

I have some error parse Json on Android Studio,
Please if you have any idea can you share where is my error.
I want to get the current exchange rate information and print it on textview.
Json/Api Url : https://api.exchangeratesapi.io/latest?base=USD
private void jsonParse() {
String SHOP_URL = "https://api.exchangeratesapi.io/latest?base=USD&symbols=EUR,GBP";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, SHOP_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("rates");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject result = jsonArray.getJSONObject(i);
int xGBP=result.getInt("GBP");
usdtry.setText(String.valueOf(xGBP));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
pRequestQueue.add(request);
}
This code not erroring but not response any..I think i have some missing.
rates is a JsonObject, not an Array.
So, your code must be
JSONObject rates = response.getJSONObject("rates");
double xGBP = rates.getDouble("GBP");
usdtry.setText(String.valueOf(xGBP));
Also, for better formatting, you can use:
DecimalFormat formatter = new DecimalFormat("###,###.##", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
usdtry.setText(formatter.format(xGBP));

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

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

cant get json data from url like www.exemple.com/json.php?apicall=cat

I am trying to get JSON data from a URL like
www.exemple.com/json.php?apicall=cat
it works nice in the browser but it doesn't work in my android application.
here is my code :
request = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
lstAnime.clear();
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
Anime anime = new Anime();
anime.setId(jsonObject.getInt("id"));
anime.setName(jsonObject.getString("name"));
anime.setDescription(jsonObject.getString("description"));
anime.setImage_url(jsonObject.getString("path"));
lstAnime.add(anime);
} catch (JSONException e) {
e.printStackTrace();
}
}
setuprecyclerview(lstAnime);
mSwipRefresh.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}
I am using volley library.
can anyone help me, please?
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);// you need to transform your response to object
arrayObject = new JSONArray(obj);//put the object in the jsonarray
for (int i = 0; i < arrayObject.length(); i++) {
JSONObject parObj = (JSONObject) parArray.get(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
I hope this helps you, Greetings!

ArrayList size zero despite adding elements

I am working on an android app.
I want to retrieve json data into an ArrayList of my data model called Expert.
Here is the code on the onCreate() method
mExpertsList = new ArrayList<Expert>();
loadData();
Log.v("RESPONSE", Integer.toString(mExpertsList.size()));
Here is the code in the function retrieving json data.
private void loadData(){
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors",
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jarray = response.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Expert expert = new Expert();
expert.setImageUrl(object.getString("image"));
expert.setName(object.getString("name"));
expert.setTopic(object.getString("country"));
expert.setRating(random.nextFloat() * ((maxRating - minRating) + minRating));
expert.setDescription(object.getString("description"));
mExpertsList.add(expert);
}
}
catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsonObjectRequest);
}
Inside loadData() method the mExpertsList shows size of 6 at end of for loop. Checked this using log messages.
But a Log statement immediately after loadData() shows that mExpertsList has size of zero.
What am I missing here?
JsonObjectRequest is an Asynchronous request so your list will be update on other thread . And you logged the size synchronously so it will print 0 always .
Access the List inside onResponse(JSONObject response);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors",
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jarray = response.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Expert expert = new Expert();
expert.setImageUrl(object.getString("image"));
expert.setName(object.getString("name"));
expert.setTopic(object.getString("country"));
expert.setRating(random.nextFloat() * ((maxRating - minRating) + minRating));
expert.setDescription(object.getString("description"));
mExpertsList.add(expert);
}
Log.v("RESPONSE", mExpertsList.size());
}
catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mExpertsList = new ArrayList<Expert>(); // You are initializing your list with size 0
loadData(); // Calling the API which will run in background
So whenever you are calling
Log.v("RESPONSE", Integer.toString(mExpertsList.size()));just after loadData() method your mExpertsList is still of size 0.
Size will change only after you get your API response.
This is an Asynchronous operation, Volley will not wait for your response and execute your next code.
If you want to print Arraylist size then print it just after for loop,
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors",
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jarray = response.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Expert expert = new Expert();
expert.setImageUrl(object.getString("image"));
expert.setName(object.getString("name"));
expert.setTopic(object.getString("country"));
expert.setRating(random.nextFloat() * ((maxRating - minRating) + minRating));
expert.setDescription(object.getString("description"));
mExpertsList.add(expert);
}
Log.v("RESPONSE", mExpertsList.size());
}
catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
It will print the exxact size of your list.
It looks like you are making some kind of asynchronous call when you call loadData():
mExpertsList = new ArrayList<Expert>();
loadData();
Log.v("RESPONSE", Integer.toString(mExpertsList.size()));
When you check the size, it is possible that onResponse(), the handler for the web call, has not yet been called. If so, then the size would still appear to be zero.
You should only be relying on the contents of mExpertsList being there if onResponse has been successfully called with actual content.
Do this change in part 1:
mExpertsList = new ArrayList<Expert>();
loadData();
//Log.v("RESPONSE", Integer.toString(mExpertsList.size()));----Comment it out
Change in part 2:
private void loadData(){
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors",
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jarray = response.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Expert expert = new Expert();
expert.setImageUrl(object.getString("image"));
expert.setName(object.getString("name"));
expert.setTopic(object.getString("country"));
expert.setRating(random.nextFloat() * ((maxRating - minRating) + minRating));
expert.setDescription(object.getString("description"));
mExpertsList.add(expert);
Log.v("RESPONSE", Integer.toString(mExpertsList.size())); //-----New ADDED
}
}
catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsonObjectRequest);
}

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