Handling a network request response in android - java

I created an android application to handle network requests using Volley API. I have managed to get a response from the server but I am failing to loop through the different objects of the result JSON and when I add data to a Listview it is only giving me the application's package name with a number added at the end.
This is the response that I want to handle.
{
"list": [
{
"dt": 1637172000,
"main": {
"temp": 301.79,
"feels_like": 300.34,
"temp_min": 298.24,
"temp_max": 301.79,
"pressure": 1008,
"sea_level": 1008,
"grnd_level": 854,
"humidity": 20,
"temp_kf": 3.55
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"clouds": {
"all": 7
},
"wind": {
"speed": 3.77,
"deg": 46,
"gust": 8.98
},
"visibility": 10000,
"pop": 0,
"sys": {
"pod": "n"
},
"dt_txt": "2021-11-17 18:00:00"
}
]
}
The object model and its fields
public class WeatherReportModel {
private int dt;
private JSONObject main;
private JSONArray weather;
private JSONObject clouds;
private JSONObject wind;
private int visibility;
private double pop;
private JSONObject sys;
private String dt_txt;
public WeatherReportModel(
int dt,
JSONObject main,
JSONArray weather,
JSONObject clouds,
JSONObject wind,
int visibility,
double pop,
JSONObject sys,
String dt_txt) {
this.dt = dt;
this.main = main;
this.weather = weather;
this.clouds = clouds;
this.wind = wind;
this.visibility = visibility;
this.pop = pop;
this.sys = sys;
this.dt_txt = dt_txt;
}
}
This is call back function which fetches the responses and add to the Model's object
public void getWeather(VolleyResponseListener forecast) {
List<WeatherReportModel> weatherReportModels = new ArrayList<>();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray weather_list = response.getJSONArray("list");
// get the first item
for (int i = 0; i < weather_list.length(); i++) {
WeatherReportModel one_day_weather = new WeatherReportModel();
JSONObject first_day_from_api = (JSONObject) weather_list.get(i);
one_day_weather.setDt(first_day_from_api.getInt("dt"));
one_day_weather.setMain(first_day_from_api.getJSONObject("main"));
one_day_weather.setWeather(first_day_from_api.getJSONArray("weather"));
one_day_weather.setClouds(first_day_from_api.getJSONObject("clouds"));
one_day_weather.setWind(first_day_from_api.getJSONObject("wind"));
one_day_weather.setVisibility(first_day_from_api.getInt("visibility"));
one_day_weather.setPop(first_day_from_api.getLong("pop"));
one_day_weather.setSys(first_day_from_api.getJSONObject("sys"));
one_day_weather.setDt_txt(first_day_from_api.getString("dt_txt"));
weatherReportModels.add(one_day_weather);
}
forecast.onResponse(weatherReportModels);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//get the property call consolidated weather
MySingleton.getInstance(context).addToRequestQueue(request);
}

Usually, ArrayAdapter when used like this will try to use toString() function to get the value and display it. Try to override the toString in the
WeatherReportModel and try again.

Related

How to call data from an API into a spinner?

I want to show a district list in a spinner, and i am getting that data through an API.
Here is an example of the response.
{
"districts": [
{
"district": "ANANTNAG"
},
{
"district": "BADGAM"
},
{
"district": "BANDIPORA"
},
{
"district": "BARAMULLA"
},
{
"district": "DODA"
},
{
"district": "GANDERBAL"
},
{
"district": "JAMMU"
},
{
"district": "KARGIL"
},
{
"district": "KATHUA"
},
{
"district": "KISHTWAR"
},
{
"district": "KULGAM"
},
{
"district": "KUPWARA"
},
{
"district": "LEH LADAKH"
},
{
"district": "POONCH"
},
{
"district": "PULWAMA"
},
{
"district": "RAJAURI"
},
{
"district": "RAMBAN"
},
{
"district": "REASI"
},
{
"district": "SAMBA"
},
{
"district": "SHOPIAN"
},
{
"district": "SRINAGAR"
},
{
"district": "UDHAMPUR"
},
{
"district": "JAMMU AND KASHMIR"
}
],
"Request_type": "districts",
"responseCode": "Success"
}
After that, I created 2 schemapojo class for response and dataList as well.
Then, I am calling this into a class but its not working!! I don't have any idea how to call an API and set the response data into a spinner.
Please help
private void getdistricts(String state) {
JSONObject mJobj = new JSONObject();
try {
mJobj.put("state", state);
mJobj.put(REQUEST, "districts");
} catch (JSONException e) {
e.printStackTrace();
}
Call<districtresponse> call = RetrofitClient.getInstance().getApi().getDistrict(mJobj);
call.enqueue(new Callback<districtresponse>() {
#Override
public void onResponse(Call<districtresponse> call, Response<districtresponse> response) {
String status = response.body().getResponseCode();
if (status.equalsIgnoreCase("Success")){
district_list = response.body().getDistricts();
districts = new ArrayAdapter<String>(this,R.layout.dist_list,district_list);
}
}
#Override
public void onFailure(Call<districtresponse> call, Throwable t) {
}
});
}
Here in code district_List variable is for a second model class where all district List is available.
I tried a different process from youtube but none of that worked !!
Change code
districts = new ArrayAdapter<String>(this,R.layout.dist_list,district_list);
To this
ArrayAdapter adapter
= new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
districts);
// set simple layout resource file
// for each item of spinner
adapter.setDropDownViewResource(
android.R.layout
.simple_spinner_dropdown_item);
// Set the ArrayAdapter (ad) data on the
// Spinner which binds data to spinner
spino.setAdapter(adapter);
You can also try like this
ArrayList<String> stringArrayList = null; //Create A global Variable
Call<Example> call = RetrofitClient.getInstance().getApi().getDistrict();
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
if (response.code() == 200) {
ArrayList<District> districts = (ArrayList<District>) response.body().getDistricts();
for (int i = 0; i < districts.size(); i++) {
stringArrayList.add(districts.get(i).getDistrict());
}
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
}
});
ArrayAdapter arrayAdapter = new ArrayAdapter(this,R.layout.dist_list,district_list,stringArrayList);
arrayAdapter.setDropDownViewResource(R.layout.dist_list,district_list);
yourSpinner.setAdapter(arrayAdapter);
And here create a model like this
Example Model Class
public class Example {
#SerializedName("districts")
#Expose
private List<District> districts = null;
#SerializedName("Request_type")
#Expose
private String requestType;
#SerializedName("responseCode")
#Expose
private String responseCode;
public List<District> getDistricts() {
return districts;
}
public void setDistricts(List<District> districts) {
this.districts = districts;
}
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
public String getResponseCode() {
return responseCode;
}
public void setResponseCode(String responseCode) {
this.responseCode = responseCode;
}
}
District Model Class
public class District {
#SerializedName("district")
#Expose
private String district;
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
}
I just hope your problem is solved using this

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")

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.

Parse JSON to fetch all the details using Asynctask

{
"response_code": 200,
"debit": 3,
"position": "Train has reached Destination and late by 5 minutes",
"train": {
"number": "12046",
"name": "CDG NDLS SHTBDI"
},
"route": [
{
"no": 1,
"day": 0,
"station": {
"name": "CHANDIGARH",
"code": "CDG"
},
"has_arrived": false,
"has_departed": true,
"distance": 0,
"scharr": "Source",
"schdep": "12:00",
"actarr": "00:00",
"actdep": "12:00",
"scharr_date": "19 Nov 2015",
"actarr_date": "19 Nov 2015",
"latemin": 0
},
{
"no": 2,
"day": 0,
"station": {
"name": "AMBALA CANT JN",
"code": "UMB"
},
"has_arrived": true,
"has_departed": true,
"distance": 67,
"scharr": "12:40",
"schdep": "12:42",
"actarr": "12:40",
"actdep": "12:42",
"scharr_date": "19 Nov 2015",
"actarr_date": "19 Nov 2015",
"latemin": 0
},
{
"no": 3,
"day": 0,
"station": {
"name": "NEW DELHI",
"code": "NDLS"
},
"has_arrived": true,
"has_departed": false,
"distance": 265,
"scharr": "15:25",
"schdep": "Destination",
"actarr": "15:30",
"actdep": "00:00",
"scharr_date": "19 Nov 2015",
"actarr_date": "19 Nov 2015",
"latemin": 5
}
]
}
public class TrainStatus {
public static int responseCode;
private int serialNo;
private String scheduleArrival;
private String actualArrival;
public static String station;
public static int debit;
private String statusOfArrival;
private boolean hasArrived;
private boolean hasDeparted;
private int latemin;
private String actualArrivalDate;
private String scheduleArrivalDate;
public static String position;
public String name;
public String getName()
{
return getName();
}
public void setName(String name)
{
this.name=name;
}
public boolean isHasArrived()
{
return hasArrived;
}
public void setHasArrived(boolean hasArrived)
{
this.hasArrived = hasArrived;
}
public boolean isHasDeparted()
{
return hasDeparted;
}
public void setHasDeparted(boolean hasDeparted)
{
this.hasDeparted = hasDeparted;
}
public int getLatemin()
{
return latemin;
}
public void setLatemin(int latemin)
{
this.latemin = latemin;
}
public void setSerialNo(int serialNo)
{
this.serialNo = serialNo;
}
public String getScheduleArrival()
{
return scheduleArrival;
}
public void setScheduleArrival(String scheduleArrival)
{
this.scheduleArrival = scheduleArrival;
}
public String getActualArrival()
{
return actualArrival;
}
public void setActualArrival(String actualArrival)
{
this.actualArrival = actualArrival;
}
public String getStation()
{
return station;
}
public void setStation(String station)
{
this.station = station;
}
public String getStatusOfArrival()
{
return statusOfArrival;
}
public void setStatusOfArrival(String statusOfArrival)
{
this.statusOfArrival = statusOfArrival;
}
public String getActualArrivalDate()
{
return actualArrivalDate;
}
public void setActualArrivalDate(String actualArrivalDate)
{
this.actualArrivalDate = actualArrivalDate;
}
public String getScheduleArrivalDate()
{
return scheduleArrivalDate;
}
public void setScheduleArrivalDate(String scheduleArrivalDate)
{
this.scheduleArrivalDate = scheduleArrivalDate;
}
}
public class TrainStatusParser {
public static List<TrainStatus> parseFeed(String content){
try
{
JSONObject jsonObject = new JSONObject(content);
List<TrainStatus> trainList = new ArrayList<>();
TrainStatus.responseCode = jsonObject.getInt("response_code");
TrainStatus.position = jsonObject.getString("position");
TrainStatus.debit=jsonObject.getInt("debit");
JSONArray route = jsonObject.getJSONArray("route");
for(int i=0;i<route.length();i++)
{
JSONObject routeObject = route.getJSONObject(i);
TrainStatus trainStatus = new TrainStatus();
if (jsonObject.has("station"))
{
JSONObject addressObject = jsonObject.getJSONObject("station");
trainStatus.name=addressObject.getString("name");
}
trainStatus.setSerialNo(routeObject.getInt("no"));
trainStatus.setScheduleArrival(routeObject.getString("scharr"));
trainStatus.setActualArrival(routeObject.getString("actarr"));
trainStatus.setStatusOfArrival(routeObject.getString("status"));
trainStatus.setHasArrived(routeObject.getBoolean("has_arrived"));
trainStatus.setHasDeparted(routeObject.getBoolean("has_departed"));
trainStatus.setLatemin(routeObject.getInt("latemin"));
trainStatus.setActualArrivalDate(routeObject.getString("actarr_date"));
trainStatus.setScheduleArrivalDate(routeObject.getString("scharr_date"));
trainList.add(trainStatus);
}
return trainList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
Everything is correctly fetched except station name
Try this following code.
for(int i=0;i<route.length();i++) {
JSONObject routeObject = route.getJSONObject(i);
TrainStatus trainStatus = new TrainStatus();
JSONObject jsonObject_station = routeObject.getJSONObject("station");
String stationname = jsonObject_station.getString("name");
String code = jsonObject_station.getString("code");
Log.d("checkvalue", " " + stationname + " " + code);
trainStatus.setSerialNo(routeObject.getInt("no"));
trainStatus.setScheduleArrival(routeObject.getString("scharr"));
trainStatus.setActualArrival(routeObject.getString("actarr"));
trainStatus.setStatusOfArrival(routeObject.getString("status"));
trainStatus.setHasArrived(routeObject.getBoolean("has_arrived"));
trainStatus.setHasDeparted(routeObject.getBoolean("has_departed"));
trainStatus.setLatemin(routeObject.getInt("latemin"));
trainStatus.setActualArrivalDate(routeObject.getString("actarr_date"));
trainStatus.setScheduleArrivalDate(routeObject.getString("scharr_date"));
trainList.add(trainStatus);
}
Use a library from Google call GSON
In your posted code for parsing each route, you have this:
JSONObject routeObject = route.getJSONObject(i);
TrainStatus trainStatus = new TrainStatus();
if (jsonObject.has("station"))
{
JSONObject addressObject = jsonObject.getJSONObject("station");
trainStatus.name=addressObject.getString("name");
}
Looks like a typo here is causing your problems. You're calling jsonObject.has("station") when you should instead be calling routeObject.has("station"). Similarly, inside the if statement you should change jsonObject.getJSONObject("station") to routeObject.getJSONObject("station").

How can i create the correct JSON data in an Android app required for a Java Jax RS REST POST Api accepting a List of JSON Objects

I have a Jax-Rs created REST endpoint as defined below:
//It will create the order for the customer who is occupying
//the table identified by the PathParam tableId
#Path("/order/{tableId}")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON )
public List<ItemOrder> giveOrder(#PathParam("tableId") int tableId, List<ItemOrder> itemOrderList){
Customer currentCustomer = Restaurant.getRestaurant().getCustomerArray().get(tableId);
for (int i = 0; i<itemOrderList.size(); i++){
currentCustomer.giveOrder(itemOrderList.get(i));
}
return itemOrderList;
}
Class ItemOrder has been defined as follows:
#XmlRootElement
public class ItemOrder {
private Item mItem;
private int mNumberOfPlates;
.....
......
.....
}
Class Item has been defined as follows:
#XmlRootElement
public class Item {
private int mItemId;
private String mName;
private float mPrice;
......
......
......
}
Now i am trying to send the JSON Post data from an Android client App as follows:
//Ordering Menu
JSONObject itemOrder1Item = new JSONObject();
JSONObject itemOrder1 = new JSONObject();
try {
itemOrder1Item.put("itemId", 11);
itemOrder1Item.put("itemName","Tea");
itemOrder1Item.put("itemPrice", 10);
itemOrder1.put("Item", itemOrder1Item);
itemOrder1.put("numberOfPlates", 10);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject itemOrder2Item = new JSONObject();
JSONObject itemOrder2 = new JSONObject();
try {
itemOrder2Item.put("itemId", 22);
itemOrder2Item.put("itemName","Coffee");
itemOrder2Item.put("itemPrice", 20);
itemOrder2.put("Item", itemOrder2Item);
itemOrder2.put("numberOfPlates", 10);
} catch (JSONException e) {
Log.d("Message",e.getMessage());
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(itemOrder1);
jsonArray.put(itemOrder2);
JSONObject itemsOrderListObj = new JSONObject();
try {
itemsOrderListObj.put("itemOrderList", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
HTTPAsyncTask asyncTask = new HTTPAsyncTask(getActivity().getApplicationContext(),c, null, itemsOrderListObj, "POST");
asyncTask.execute("http://10.0.2.2:8080/restaurant1/webapi/restaurant/waiters/menus/order/2");
}
But it is throwing some error saying the POST data is not correct. While developing the REST Api i have seen that the server is able to accept data as follows:
[
{
"item": {
"itemId": 11,
"itemName": "Tea",
"itemPrice": 10
},
"numberOfPlates": 5
},
{
"item": {
"itemId": 22,
"itemName": "Coffee",
"itemPrice": 20
},
"numberOfPlates": 5
},
{
"item": {
"itemId": 33,
"itemName": "Bread",
"itemPrice": 30
},
"numberOfPlates": 5
}
]
Now how will i be able to create this JSON Data in my Android app.
Need the help badly.
Used GSON. Its pretty simple as follows;
List<ItemOrder> itemsOrderListObj = new ArrayList<>();
itemsOrderListObj.add(new ItemOrder(new Item(11, "Tea", 10), 10));
itemsOrderListObj.add(new ItemOrder(new Item(22, "Coffee", 20), 10));
itemsOrderListObj.add(new ItemOrder(new Item(33, "Bread", 30), 10));
String itemsOrderListStringJSON = new Gson().toJson(itemsOrderListObj);
Log.i("JSONPOSTDATA", itemsOrderListStringJSON );
HTTPAsyncTask asyncTask = new HTTPAsyncTask(getActivity().getApplicationContext(),c, null, itemsOrderListStringJSON, "POST");
asyncTask.execute("http://10.0.2.2:8080/restaurant1/webapi/restaurant/waiters/menus/order/2");

Categories

Resources