How to get ArrayList using GET method of volley - java

This is the example of ArrayList that i need to fetch, how to fetch this Arrays? Im using GET method of volley to fetch this Array and show in Recycler View.
[
{
"_id": "a2a1",
"name": "Flower",
"image": {
"_id": "a2a2",
"name": "flower.jpg",
"url": "/uploads/c8c8c.jpg",
"related": [
"a2a1"
],
"id": "0a2a2"
},
},
{
"_id": "433d",
"name": "Bouquet",
"id": "433d",
"image": {
"_id": "433e",
"name": "baloon.jpg",
"url": "/uploads/247db.jpg",
"related": [
"433d"
],
"id": "433e"
},
}]
This is my code by using Get method of Volley to fetch the array, i already put the correct api but i didnt get the list of the array.
private void FlowerList(){
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL_FLOWER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
FlowerModel[] models = gson.fromJson(String.valueOf(json.getJSONArray(null)), FlowerModel[].class);
flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(getContext()).add(request);
}

if you are using Gson verson 2.8' then
try {
json = new JSONObject(response);
ArrayList<FlowerModel> models = gson.fromJson(response, TypeToken.getParameterized(ArrayList.class, FlowerModel.class).getType());
//flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
for older version
try {
json = new JSONObject(response);
ArrayList<FlowerModel> models = gson.fromJson(response, new TypeToken<ArrayList<FlowerModel>>(){}.getType(););
//flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}

try this....i have modified your code
ArrayList<String> stringArrayList;
String id1,name,id2;
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL_FLOWER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
JSONArray jsonArray=json.getJSONArray("Your_response_arrayName");
stringArrayList=new ArrayList<>();
for(i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
stringArrayList.add(jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(getContext()).add(request);
}
hope this will help you

Related

android volley POST jsonArray update

I have a problem in using volley Rest API Post Request
I am not sure is it required to use Map but here I didn't use it.
I'm trying to update my jSONArray from this :
[
{
"id": 1,
"num1": "1",
"num2": "0",
"num3": "1",
"num4": "0"
}
]
into this :
[
{
"id": 1,
"num1": "1",
"num2": "1",
"num3": "1",
"num4": "0"
}
]
Following is my code( I used volley Post request for this ) :
RequestQueue queue = Volley.newRequestQueue(Rele.this);
String url = "https://mysite.dev/fdfh2g/data";
JsonArrayRequest request = new JsonArrayRequest
(Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Integer num2val = 1 ;
try {
JSONObject Info = response.getJSONObject(0);
Info.put("num2",num2val);
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
}
});
queue.add(request);
but instead I'm getting this :
[
{
"id": 1,
"num1": "1",
"num2": "1",
"num3": "1",
"num4": "0"
},
{
"id": 2
}
]

Having trouble parsing json using volley

I'm trying to get data from flickr API, using volley lib.
this is my json :
{
"photos": {
"page": 1,
"pages": 48,
"perpage": 100,
"total": "4793",
"photo": [
{
*"id": "48955365182",
"owner": "49191827#N00",
*"secret": "fd5e5fd91c",
*"server": "65535",
* "farm": 66,
"title": "permitted burn. thermal, ca. 2019.",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
}, ...
}
}
I'm trying to get the fields with " * ":
private void parseJson() {
String URL = "https://www.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=x&user_id=49191827%40N00&extras=&format=json&nojsoncallback=1";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray ;
try {
jsonArray = response.getJSONArray("photo");
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Log.d("GGG",jsonObject.getString("secret"));
Log.d("GGG",jsonObject.getString("id"));
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("VVV",e.getMessage());
}
}
}, new Response.ErrorListener() {
}
}
);
}
You need to parse from the very top object
jsonArray = response.getJSONObject("photos").getJSONArray("photo")

Array inside an array - Java Codes

I am new at programming. I have this problem of fetching the values from sub array entitled "subresult". I have code of getting values from an array but it seems that it only gets the outer array and disregard the inner array. It is sad that I have no luck in this. Please respect my question because I'm just a beginner. Hoping an answer from you guys. Thank you!
JSON:
{
"result":[
{
"commonname":"Tamaraw",
"subresult":[
{
"latitude":"13.088847376649245",
"longitude":"121.0535496566772",
"province":"Mindoro"
},
{
"latitude":"14.898346071682198",
"longitude":"121.42616213302608",
"province":"General nakar"
},
{
"latitude":"14.44133541176629",
"longitude":"120.45936525802608",
"province":"Bataan"
}
]
},
{
"commonname":"Philippine Tarsier",
"subresult":[
{
"latitude":"9.810806171435631",
"longitude":"124.26143093023506",
"province":"Bohol"
}
]
},
{
"commonname":"Philippine Eagle",
"subresult":[
{
"latitude":"7.2396901503428",
"longitude":"125.44315069027664",
"province":"Davao City"
}
]
},
{
"commonname":"Visayan Warty Pig",
"subresult":[
{
"latitude":"9.651642644962154",
"longitude":"122.84131398239595",
"province":"Panay And Negros"
}
]
},
{
"commonname":"Philippine Fresh Water Crocodile",
"subresult":[
{
"latitude":"13.093068957060206",
"longitude":"121.06598892373722",
"province":"Mindoro"
}
]
},
{
"commonname":"Walden's Hornbill",
"subresult":[
{
"latitude":"10.071930427284427",
"longitude":"125.59779391691245",
"province":"Camiguin Sur and Dinagat Island"
},
{
"latitude":"14.656674396646768",
"longitude":"121.05812014083858",
"province":"Quezon"
}
]
},
{
"commonname":"Philippine Cockatoo",
"subresult":[
{
"latitude":"9.380944735295179",
"longitude":"118.38456063371927",
"province":"Palawan"
},
{
"latitude":"15.491670747921509",
"longitude":"120.94052188562534",
"province":"Cabanatuan City"
},
{
"latitude":"15.378556159943873",
"longitude":"121.39594973068233",
"province":"Dingalan"
}
]
},
{
"commonname":"Negros Bleeding-heart",
"subresult":[
{
"latitude":"9.551081019434731",
"longitude":"123.09185859510103",
"province":"Negros and Panay"
}
]
},
{
"commonname":"Philippine naked-backed fruit bat",
"subresult":[
{
"latitude":"9.646007526813666",
"longitude":"122.85255472090171",
"province":"Negros"
}
]
},
{
"commonname":"Philippine Forest Turtle",
"subresult":[
{
"latitude":"9.35368808473656",
"longitude":"118.36544272849846",
"province":"Palawan"
}
]
},
{
"commonname":"Dinagat bushy-tailed Cloud Rat",
"subresult":[
{
"latitude":"10.100726050965035",
"longitude":"125.59963979398412",
"province":"Dinagat Island"
}
]
},
{
"commonname":"Hawksbill Sea Turtle",
"subresult":[
{
"latitude":"6.984796116278719",
"longitude":"122.02642351890961",
"province":"Zamboanga"
}
]
},
{
"commonname":"Philippine Spotted Deer",
"subresult":[
{
"latitude":"16.229997551983594",
"longitude":"120.52623997214562",
"province":"Baguio"
}
]
}
]
}
Java code:
public JSONArray result;
public static final String JSON_ARRAY = "result";
public static final String TAG_COMMONNAME= "commonname";
public void getData(){
//Creating a string request
StringRequest stringRequests = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jo = null;
try {
//Parsing the fetched Json String to JSON Object
jo = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = jo.getJSONArray(JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getAnimals(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequests);
}
public void getAnimals(JSONArray ja){
//Traversing through all the items in the json array
for(int i=0;i<ja.length();i++){
try {
//Getting json object
json = ja.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(TAG_COMMONNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getAnimals(JSONArray ja){
//Traversing through all the items in the json array
for(int i=0;i<ja.length();i++){
try {
//Getting json object
json = ja.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(TAG_COMMONNAME));
//TRY THIS
JsonArray subResultJsonArray = json.optJSONArray("subresult");
} catch (JSONException e) {
e.printStackTrace();
}
}

How can i get the data from array inside an array android studio JSONArray

I am getting response from API as a JSONarray and I can get the data into my arraymodel but the problem is I need some specific data from one array and I don't have any idea how to do that.
the array is:
"history": [
{
"id": "20",
"code": "mcw_5b97de588ce0c",
"date": "2018-09-11 17:25:12",
"status": "1",
"name": "a:1:{s:7:\"english\";s:9:\"rent bill\";}",
"img": "shop.png"
}
I want the English, S:9 and the rent bill data from name.
I am posting my code here so you can understand what I have done and what mistake i'm committing.
public void shopListing()
{
showSimpleProgressDialog(this, "Loading...","Fetching Shops History",false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, shopurl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("strrrrr", ">>" + response);
try {
JSONObject obj = new JSONObject(response);
//if(obj.optString("status").equals("true")){
dataModelArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray("history");
for (int i = 0; i < dataArray.length(); i++) {
shopModel playerModel = new shopModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playerModel.setId(dataobj.getString("id"));
playerModel.setName(dataobj.getString("name"));
playerModel.setDetails(dataobj.getString("date"));
dataModelArrayList.add(playerModel);
}
setupListview();
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String api = getApi_key();
String user = getUser_key();
Map<String, String> param = new HashMap<> ();
param.put("api_key", api);
param.put("user_key", user);
return param;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Your server response is not good. instead of sending name as a string to you, it should return you "name" as an object like this:
"history": [
{
"id": "20",
"code": "mcw_5b97de588ce0c",
"date": "2018-09-11 17:25:12",
"status": "1",
"name":
{
"s":7,
"subject":"english",
"s":9,
"any_key":"rent bill"
},
"img": "shop.png"
}
I feel like server is returning you code string which you have written to process request from client. Please double check.

Can't compile the code with getting the value from JsonObject

I use Volley library to make API request to Google Places.
The response is an object like this:
{
"html_attributions": [],
"results": [
{
"address": "Wood Quay, Dublin, Ireland",
"name": "Christ Church Cathedral",
"place_id": "ChIJGw9ASiYMZ0gRy9yiaCZxNZI",
},
{ ... },
{ ... },
],
"status": "OK"
}
Inside the Response.Listener I need to access the "results" array.
I try to get the JSONArray with name "results" as follows:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, API_URL, null,
new Response.Listener <JSONObject> () {
#Override
public void onResponse(JSONObject response) {
// THE PROBLEM IS HERE - WON'T COMPILE !!!
JSONArray array = response.getJSONArray("results");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//
}
});
But I see an error:
Seems like response.getJSONArray("results"); throws the JSONException. You need to handle that exception by wrapping response.getJSONArray("results"); with a try-catch block.
Something like this:
try {
JSONArray array = response.getJSONArray("results");
} catch (org.json.JSONException exception) {
// handle the exception
}

Categories

Resources