please advise. I have a complex json object which I get requesting to openweathermap API using Retrofit and GSONConverterFactory. I have a trouble requesting forecast for 5 days, I can't populate my Recyclerview with the data, something goes wrong. I can't get what should I write in the onResponse method of Retrofit callback.
Retrofit requests are all with code 200 and message OK. So trouble is not in this area.
Thank you in advance!
Here is structure of Json object
WeatherData is a root Object which I get parsing my Json, please find the code below. All the code for it (as well as for other POJO's is imported from jsonschema2pojo:
public class WeatherData {
#SerializedName("coord")
#Expose
private Coord coord;
#SerializedName("weather")
#Expose
private List<Weather> weather = null;
#SerializedName("base")
#Expose
private String base;
#SerializedName("main")
#Expose
private Main main;
#SerializedName("visibility")
#Expose
private Integer visibility;
#SerializedName("wind")
#Expose
private Wind wind;
#SerializedName("clouds")
#Expose
private Clouds clouds;
#SerializedName("dt")
#Expose
private Long dt;
#SerializedName("sys")
#Expose
private Sys sys;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("cod")
#Expose
private Integer cod;
public Coord getCoord() {
return coord;
}
public void setCoord(Coord coord) {
this.coord = coord;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public Integer getVisibility() {
return visibility;
}
public void setVisibility(Integer visibility) {
this.visibility = visibility;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Long getDt() {
return dt;
}
public void setDt(Long dt) {
this.dt = dt;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCod() {
return cod;
}
public void setCod(Integer cod) {
this.cod = cod;
}
Here is my RecyclerView.Adapter
public class Forecast5DaysAdapter extends RecyclerView.Adapter<Forecast5DaysAdapter.ForecastHolder> {
List<WeatherData> mWeatherDataList;
public static class ForecastHolder extends RecyclerView.ViewHolder {
public TextView dateOnDate;
public ImageView weatherOnDate;
public TextView tempOnDate;
public TextView windSpeedOnDate;
public ForecastHolder(View view) {
super(view);
dateOnDate = (TextView) view.findViewById(R.id.dateOnDate);
windSpeedOnDate = (TextView) view.findViewById(R.id.windSpeedOnDate);
tempOnDate = (TextView) view.findViewById(R.id.tempOnDate);
weatherOnDate = (ImageView) view.findViewById(R.id.imageOnDate);
}
}
public Forecast5DaysAdapter(List<WeatherData> mWeatherDataList) {
this.mWeatherDataList = mWeatherDataList;
}
#Override
public ForecastHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.forecast_card, parent, false);
final ForecastHolder forecastHolder = new ForecastHolder(view);
return forecastHolder;
}
#Override
public void onBindViewHolder(ForecastHolder holder, int position) {
//FILLING THE CARDS IN RECYCLERVIEW WITH INFORMATION
holder.dateOnDate.setText(mWeatherDataList.get(position).getDt().toString());
holder.tempOnDate.setText(mWeatherDataList.get(position).getMain().getTemp().toString());
holder.windSpeedOnDate.setText(mWeatherDataList.get(position).getWind().getSpeed().toString());
Picasso.with(holder.weatherOnDate.getContext()).load("http://openweathermap.org/img/w/" + mWeatherDataList.get(position).getWeather().get(position).getIcon() + ".png").into(holder.weatherOnDate);
}
#Override
public int getItemCount() {
return 0;
}
Here is the class I want to display the Recyclerview
public class Forecast5Days extends AppCompatActivity {
private static final String API_KEY = "HERE IS THE KEY";
private RecyclerView forecastRecycler;
private ArrayList<WeatherData> mWeatherData;
private Forecast5DaysAdapter forecast5DaysAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forecast_5_days);
forecastRecycler = (RecyclerView) findViewById(R.id.forecast_5_daysRecycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
forecastRecycler.setLayoutManager(layoutManager);
final Forecast5DaysAdapter forecast5DaysAdapter = new Forecast5DaysAdapter(mWeatherData);
forecastRecycler.setAdapter(forecast5DaysAdapter);
Intent intent = getIntent();
final String cityName = intent.getStringExtra("cityName");
if (!cityName.isEmpty()) {
Call<WeatherData> call = RetrofitBuilderHelper.weatherAPI.getForecast5Days(cityName, "ru", "metric", API_KEY);
call.enqueue(new Callback<WeatherData>() {
#Override
public void onResponse(Call<WeatherData> call, Response<WeatherData> response) {
//????????????????
}
#Override
public void onFailure(Call<WeatherData> call, Throwable t) {
Toast toast = Toast.makeText(Forecast5Days.this, "Something went wrong with request", Toast.LENGTH_LONG);
toast.show();
}
});
} else {
Toast toast = Toast.makeText(Forecast5Days.this, "Something went wrong with intent", Toast.LENGTH_LONG);
toast.show();
}
}
Your onResponse should be like this
call.enqueue(new Callback<WeatherData>() {
#Override
public void onResponse(Call<WeatherData> call, Response<WeatherData> response) {
if(response.isSuccessful() && response.body != null) {
WeatherData data = response.body();
}
}
#Override
public void onFailure(Call<WeatherData> call, Throwable t) {
Toast toast = Toast.makeText(Forecast5Days.this, "Something went wrong with request", Toast.LENGTH_LONG);
toast.show();
}
});
Also your Call is Call<WeatherData> which will give you a single object. If you want a list of objects your call should be Call<List<WeatherData>>
I think you are looking to pass Weatherinstead of WeatherData so your onResponse should look like
call.enqueue(new Callback<WeatherData>() {
#Override
public void onResponse(Call<WeatherData> call, Response<WeatherData> response) {
if(response.isSuccessful() && response.body != null) {
WeatherData data = response.body();
List<Weather> weatherList = data.getWeatherList();
//Pass this list to your adapter
}
}
#Override
public void onFailure(Call<WeatherData> call, Throwable t) {
Toast toast = Toast.makeText(Forecast5Days.this, "Something went wrong with request", Toast.LENGTH_LONG);
toast.show();
}
});
Your JSON return is a List not only a Single WeatherData Object.
So all you should have to do is a cange of the Expected return value.
Try this:
Call<List<WeatherData>> call = RetrofitBuilderHelper.weatherAPI.getForecast5Days(cityName, "ru", "metric", API_KEY);
call.enqueue(new Callback<List<WeatherData>>() {
#Override
public void onResponse(Call<List<WeatherData>> call, Response<List<WeatherData>> response) {
forecastRecycler.weatherList = response.body();
forecastRecycler.notifyDatasetChanged();
}
Related
I am trying to communicate with an API using Retrofit in Android Studios but do not know how to get the JSON array within a JSON object.
JSON:
{
"result":{
"status":{
"msg":"success",
"code":200,
"action":2,
"execution_time":"0.505"
},
"page":"1",
"page_size":"40",
"q":"iphone",
"sort":"default",
"tmall":false,
"free_shiping":false,
"total_results":1924963,
"ip":"13.228.169.5",
"item":[
{
"num_iid":619354061232,
"pic":"https://img.alicdn.com/bao/uploaded/i4/2150908574/O1CN01O3Akm82DCwTChbTXg_!!2150908574.jpg",
"title":"Apple/苹果 iPhone XR iphone xs max手机双卡国行原装4G xr苹果x",
"price":"6000",
"promotion_price":"2009",
"sales":1973,
"loc":"广东 深圳",
"seller_id":2150908574,
"seller_nick":"实惠馆超市",
"shop_title":"新魔方数码",
"user_type":0,
"detail_url":"https://item.taobao.com/item.htm?id=619354061232",
"delivery_fee":"0.00"
}
"item":[...]
Method:
private void taobaoSearch(){
TaobaoInterface retrofitInterface = RetrofitInstance.getRetrofitInstanceTaobao().create(TaobaoInterface.class);
Call<TaobaoModel> listCall = retrofitInterface.getTaobao("item_search", "40","default", "iphone","taobao-api.p.rapidapi.com", "//apikey hidden");
listCall.enqueue(new Callback<TaobaoModel>() {
#Override
public void onResponse(Call<TaobaoModel> call, Response<TaobaoModel> response) {
//not sure what to do here
}
#Override
public void onFailure(Call<TaobaoModel> call, Throwable t) {
System.out.println("FAILED");
System.out.println(call);
t.printStackTrace();
}
});
}
TaobaoModel:
public class TaobaoModel {
#SerializedName("result")
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
Result:
public class Result {
#SerializedName("status")
private Status status;
#SerializedName("q")
private String q;
#SerializedName("page")
private String page;
#SerializedName("page_size")
private String page_size;
#SerializedName("total_results")
private int total_results;
#SerializedName("tmall")
private String tmall;
#SerializedName("sort")
private String sort;
#SerializedName("free_shiping")
private String free_shiping;
#SerializedName("ip")
private String ip;
#SerializedName("item")
private ArrayList<TaobaoItems> item;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getQ() {
return q;
}
public void setQ(String q) {
this.q = q;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getPage_size() {
return page_size;
}
public void setPage_size(String page_size) {
this.page_size = page_size;
}
public int getTotal_results() {
return total_results;
}
public void setTotal_results(int total_results) {
this.total_results = total_results;
}
public String getTmall() {
return tmall;
}
public void setTmall(String tmall) {
this.tmall = tmall;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getFree_shiping() {
return free_shiping;
}
public void setFree_shiping(String free_shiping) {
this.free_shiping = free_shiping;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public ArrayList<TaobaoItems> getItem() {
return item;
}
public void setItem(ArrayList<TaobaoItems> item) {
this.item = item;
}
}
TaobaoItems
public class TaobaoItems {
#SerializedName("num_iid")
private long num_iid;
#SerializedName("pic")
private String pic;
#SerializedName("title")
private String title;
#SerializedName("price")
private String price;
#SerializedName("promotion_price")
private String promotion_price;
#SerializedName("sales")
private int sales;
#SerializedName("loc")
private String loc;
#SerializedName("seller_id")
private long seller_id;
#SerializedName("seller_nick")
private String seller_nick;
#SerializedName("shop_title")
private String shop_title;
#SerializedName("user_type")
private int user_type;
#SerializedName("detail_url")
private String detail_url;
#SerializedName("delivery_fee")
private String delivery_fee;
public TaobaoItems(String title, String price, String pic, String detail_url) {
this.pic = pic;
this.title = title;
this.price = price;
this.detail_url = detail_url;
}
public long getNum_iid() {
return num_iid;
}
public void setNum_iid(long num_iid) {
this.num_iid = num_iid;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getPromotion_price() {
return promotion_price;
}
public void setPromotion_price(String promotion_price) {
this.promotion_price = promotion_price;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public long getSeller_id() {
return seller_id;
}
public void setSeller_id(long seller_id) {
this.seller_id = seller_id;
}
public String getSeller_nick() {
return seller_nick;
}
public void setSeller_nick(String seller_nick) {
this.seller_nick = seller_nick;
}
public String getShop_title() {
return shop_title;
}
public void setShop_title(String shop_title) {
this.shop_title = shop_title;
}
public int getUser_type() {
return user_type;
}
public void setUser_type(int user_type) {
this.user_type = user_type;
}
public String getDetail_url() {
return detail_url;
}
public void setDetail_url(String detail_url) {
this.detail_url = detail_url;
}
public String getDelivery_fee() {
return delivery_fee;
}
public void setDelivery_fee(String delivery_fee) {
this.delivery_fee = delivery_fee;
}
}
Status:
public class Status {
#SerializedName("msg")
private String msg;
#SerializedName("code")
private int code;
#SerializedName("action")
private int action;
#SerializedName("execution_time")
private String execution_time;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
public String getExecution_time() {
return execution_time;
}
public void setExecution_time(String execution_time) {
this.execution_time = execution_time;
}
}
My intention is to get the JSON Array item and display title,price,pic,detail_url from it. I found out how to display it one at a time so far, but couldn't find how to iterate the JSON object so that I can display the data in a listview. Please help, I am new to this and I've been stuck for quite awhile now. If you want to see my interface, retrofit instance etc just let me know.
private void taobaoSearch(){
TaobaoInterface retrofitInterface = RetrofitInstance.getRetrofitInstanceTaobao().create(TaobaoInterface.class);
Call<TaobaoModel> listCall = retrofitInterface.getTaobao("item_search", "40","default", "iphone","taobao-api.p.rapidapi.com", "//apikey hidden");
listCall.enqueue(new Callback<TaobaoModel>() {
#Override
public void onResponse(Call<TaobaoModel> call, Response<TaobaoModel> response) {
List<Result> retro=response.body().getitems();
generateDataList(retro);
}
#Override
public void onFailure(Call<TaobaoModel> call, Throwable t) {
System.out.println("FAILED");
System.out.println(call);
t.printStackTrace();
}
});
}
/*Method to generate List of data using RecyclerView with custom adapter*/
private void generateDataList(List<Result> dataList) {
recyclerView = findViewById(R.id.customRecycler);
adapter = new CustomAdapter(this,dataList);
recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}
I am trying to parse response from server in Android studio.
But I am not getting all values in Arraylist.
I have created ItemData.java and ItemResponse.java
I am Calling Api using getItemData Method:
public void getItemData() {
Call<ItemDataResponse> call = service.getData(token, "200");
call.enqueue(new Callback<ItemDataResponse>() {
#Override
public void onResponse(#NonNull Call<ItemDataResponse> call, #NonNull Response<ItemDataResponse> response) {
Log.d("dataFromServer", response.body.toString());
}
#Override
public void onFailure(#NonNull Call<ItemDataResponse> call, #NonNull Throwable t) {
progressDoalog.dismiss();
Toast.makeText(LiveVehiclesActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
This is Json response:
{
"code":"1",
"items":[
{
"item_id":"200",
"speed":"2"
},
{
"item_id":"201",
"speed":"0"
}
]
}
ItemsResponse.java:
public class ItemDataResponse implements Serializable {
#SerializedName("code")
private String code;
#SerializedName("items")
#Expose
private List<ItemData> items;
public String getResponsecode() {
return responsecode;
}
public void setResponsecode(String responsecode) {
this.responsecode = responsecode;
}
public List<ItemData> getItems() {
return items;
}
public void setItems(List<ItemData> items) {
this.items = items;
}
}
ItemData.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ItemData {
#SerializedName("item_id")
#Expose
private String itemId;
#SerializedName("speed")
#Expose
private String speed;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
}
After run in debug mode I am getting response like:
code:"1"
items=null
your should modify
class ItemData {
private String item_id;
private String speed;
public String getItem_id() {
return item_id;
}
public void setItem_id(String item_id) {
this.item_id = item_id;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
}
The ItemData model does not seem to be consistent with the JSON response.
i.e
{
"item_id":"200",
"speed":"2"
}
should map to:
class ItemData implements Serializable {
#SerializedName("item_id")
private String itemId;
#SerializedName("speed")
private String speed;
// getters and setters
}
Use SerializedName attribute for the field contains "_". Here for item_id in your ItemData class getting problem in mapping.
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ItemData {
#SerializedName("item_id")
#Expose
private String itemId;
#SerializedName("speed")
#Expose
private String speed;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
}
please change your ItemDataResponse class also
public class ItemDataResponse {
#SerializedName("code")
#Expose
private String code;
#SerializedName("items")
#Expose
private List<Item> items = null;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
I'm creating a weather app using the openweathermap api, and need to access the elements of a json array called "list". It contains the weather forecast for the next several days. I'm using retrofit to parse all the json data as well. Problem is that I cannot access the array at all. I can access the elements of city, however.
json structure
main class
forecast output data
forecast list
forecast item
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.openweathermap.org")
.addConverterFactory(JacksonConverterFactory.create())
.build();
final WeatherService service = retrofit.create(WeatherService.class);
final WeatherForecast forecast = retrofit.create(WeatherForecast.class);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Call<ForecastOutputData> callForecastRequest = forecast.getWeatherInfo(Double.toString(lat), Double.toString(lon), "imperial", "5", "key");
callForecastRequest.enqueue(new Callback<ForecastOutputData>() {
#Override
public void onResponse(Call<ForecastOutputData> forecastCall, Response<ForecastOutputData> forecastResponse) {
ForecastOutputData forecastData = forecastResponse.body();
Log.d("GHEY",forecastData.getCity().getName());
Test.setText("Test " + forecastData.getList);
}
#Override
public void onFailure(Call<ForecastOutputData> call, Throwable t) {
Log.e("mytag", "mymessage",t);
Test.setText("Test FAIL");
}
});
}
});
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class ForecastOutputData {
private int cnt;
private String cod;
private double message;
private List<ForecastList> forecastData;
private City city;
public String getCod() {
return cod;
}
public void setCod(String cod) {
this.cod = cod;
}
public int getCnt() {
return cnt;
}
public void setCnt(int cnt) {
this.cnt = cnt;
}
public List<ForecastList> getForecastData() {
return forecastData;
}
public void setForecastData(List<ForecastList> forecastData) {
this.forecastData = forecastData;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public double getMessage() {
return message;
}
public void setMessage(double message) {
this.message = message;
}
}
import java.util.List;
class ForecastList {
private int dt;
private Main main;
private List<Weather> weather;
private Clouds clouds;
private Wind wind;
private Sys sys;
private String dtTxt;
public int getDt() {
return dt;
}
public void setDt(int dt) {
this.dt = dt;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public String getDtTxt() {
return dtTxt;
}
public void setDtTxt(String dtTxt) {
this.dtTxt = dtTxt;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
public class ForecastItem {
private String cod;
private double message;
private int cnt;
private List<ForecastList> list;
private City city;
public String getCod() {
return cod;
}
public void setCod(String cod) {
this.cod = cod;
}
public double getMessage() {
return message;
}
public void setMessage(double message) {
this.message = message;
}
public int getCnt() {
return cnt;
}
public void setCnt(int cnt) {
this.cnt = cnt;
}
public List<ForecastList> getList() {
return list;
}
public void setList(List<ForecastList> list) {
this.list = list;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
}
Try it
#JsonIgnoreProperties(ignoreUnknown = true)
class ForecastResponse {
private String cod;
private String message;
private City city;
#JsonProperty("list")
private List<ForecastItem> list;
}
public class ForecastItem {
private int dt;
//dt, main, weather, clouds etc
}
I am reading a JSON like this:
{
"matches": [{
"id": 246119,
"utcDate": "2018-08-17T18:15:00Z",
"status": "FINISHED",
"homeTeam": {
"id": 298,
"name": "Girona FC"
},
"awayTeam": {
"id": 250,
"name": "Real Valladolid CF"
},
"score": {
"winner": "DRAW",
"duration": "REGULAR"
}
}]
}
I must say that the JSON is valid. I am consuming this JSON through an API. I can correctly read the properties "id", "utc" and "status", but I could not with "score", "awayTeam" and "homeTeam". I don't really know how to work those properties. I'd like to handle each propertie of score, awayTeam, and homeTeam individually, for example, I want to get just the name of awayTeam and homeTeam and the 2 properties of score.
This, is my code:
MainActivity
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
private static final String TAG = "Football";
private RecyclerView recyclerView;
private ListaPartidosAdapter listaPartidosAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
listaPartidosAdapter = new ListaPartidosAdapter(this);
recyclerView.setAdapter(listaPartidosAdapter);
recyclerView.setHasFixedSize(true);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this, VERTICAL, true);
recyclerView.setLayoutManager(layoutManager);
retrofit = new Retrofit.Builder()
.baseUrl("http://api.football-data.org/v2/")
.addConverterFactory(GsonConverterFactory.create())
.build();
obtenerDatos();
}
private void obtenerDatos() {
footballdataService service = retrofit.create(footballdataService.class);
Call<PartidosRespuesta> partidosRespuestaCall = service.obtenerlistaPartidos();
partidosRespuestaCall.enqueue(new Callback<PartidosRespuesta>() {
#Override
public void onResponse(Call<PartidosRespuesta> call, Response<PartidosRespuesta> response) {
if(response.isSuccessful()) {
PartidosRespuesta partidosRespuesta = response.body();
ArrayList<Partido> listaPartidos = partidosRespuesta.getMatches();
listaPartidosAdapter.adicionarListaPartidos(listaPartidos);
}
else {
Log.e(TAG, "onResponse: " + response.errorBody());
}
}
#Override
public void onFailure(Call<PartidosRespuesta> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
}
Now this is my interface. footballdataService
public interface footballdataService {
#GET("competitions/2014/matches")
Call<PartidosRespuesta> obtenerlistaPartidos();
}
This is PartidosRespuestas class
public class PartidosRespuesta {
private ArrayList<Partido> matches;
public ArrayList<Partido> getMatches() {
return matches;
}
public void setMatches(ArrayList<Partido> matches) {
this.matches = matches;
}
}
This, is the adapter.
public class ListaPartidosAdapter extends RecyclerView.Adapter<ListaPartidosAdapter.ViewHolder> {
private static final String TAG = "Football_Adapter";
private ArrayList<Partido> dataset;
private Context context;
public ListaPartidosAdapter(Context context) {
this.context = context;
dataset = new ArrayList<Partido>();
}
#Override
public ListaPartidosAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_partidos, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
Partido p = dataset.get(position);
holder.status.setText(p.getId());
}
#Override
public int getItemCount() {
return dataset.size();
}
public void adicionarListaPartidos(ArrayList<Partido> listaPartidos){
dataset.addAll(listaPartidos);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView status;
public ViewHolder(View itemView) {
super(itemView);
status = (TextView) itemView.findViewById(R.id.status);
}
}
}
And this.., is Partido class
public class Partido {
private String id;
private String utcDate;
private String status;
private EquipoCasa homeTeam;
private EquipoVisita AwayTeam;
private Puntaje score;
public String getId() {
return id;
}
public String getUtcDate() {
return utcDate;
}
public String getStatus() {
return status;
}
public EquipoCasa getHomeTeam() {
return homeTeam;
}
public EquipoVisita getAwayTeam() {
return AwayTeam;
}
public Puntaje getScore() {
return score;
}
public void setId(String id) {
this.id = id;
}
public void setUtcDate(String utcDate) {
this.utcDate = utcDate;
}
public void setStatus(String status) {
this.status = status;
}
public void setHomeTeam(EquipoCasa homeTeam) {
this.homeTeam = homeTeam;
}
public void setAwayTeam(EquipoVisita awayTeam) {
AwayTeam = awayTeam;
}
public void setScore(Puntaje score) {
this.score = score;
}
public class EquipoCasa {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class EquipoVisita {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Puntaje {
private String winner;
private String duration;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
}
POJO classes of your code should this:
AwayTeam.java
//AwayTeam
public class AwayTeam {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
PartidosRespuesta.java
//Object response
public class PartidosRespuesta {
#SerializedName("matches")
#Expose
private List<Match> matches = null;
public List<Match> getMatches() {
return matches;
}
public void setMatches(List<Match> matches) {
this.matches = matches;
}
}
HomeTeam.java
//HomeTeam
public class HomeTeam {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Score.java
//Score
public class Score {
#SerializedName("winner")
#Expose
private String winner;
#SerializedName("duration")
#Expose
private String duration;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
Edit:
#Override
public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
Partido p = dataset.get(position);
HomeTeam homeTeam = p.getHomeTeam();
String nameHomeTeam = homeTeam.getName();
}
And tool convert json to java code: http://www.jsonschema2pojo.org/
try
public class Puntaje {
public String winner;
public String duration;
}
It's seems like you've problems with your models. Use this link to convert your json to java object.
I'm trying to use GSON with my OpenWeatherMap API. I was able to parse my JSON into the following code:
public class List {
#SerializedName("dt")
#Expose
private Integer dt;
#SerializedName("main")
#Expose
private Main main;
#SerializedName("weather")
#Expose
private java.util.List<Weather> weather = null;
#SerializedName("clouds")
#Expose
private Clouds clouds;
#SerializedName("wind")
#Expose
private Wind wind;
#SerializedName("rain")
#Expose
private Rain rain;
#SerializedName("sys")
#Expose
private Sys sys;
#SerializedName("dt_txt")
#Expose
private String dtTxt;
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public java.util.List<Weather> getWeather() {
return weather;
}
public void setWeather(java.util.List<Weather> weather) {
this.weather = weather;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Rain getRain() {
return rain;
}
public void setRain(Rain rain) {
this.rain = rain;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public String getDtTxt() {
return dtTxt;
}
public void setDtTxt(String dtTxt) {
this.dtTxt = dtTxt;
}
}
public class Main {
#SerializedName("temp")
#Expose
private Double temp;
#SerializedName("temp_min")
#Expose
private Double tempMin;
#SerializedName("temp_max")
#Expose
private Double tempMax;
#SerializedName("pressure")
#Expose
private Double pressure;
#SerializedName("sea_level")
#Expose
private Double seaLevel;
#SerializedName("grnd_level")
#Expose
private Double grndLevel;
#SerializedName("humidity")
#Expose
private Integer humidity;
#SerializedName("temp_kf")
#Expose
private Integer tempKf;
public Double getTemp() {
return temp;
}
public void setTemp(Double temp) {
this.temp = temp;
}
public Double getTempMin() {
return tempMin;
}
public void setTempMin(Double tempMin) {
this.tempMin = tempMin;
}
public Double getTempMax() {
return tempMax;
}
public void setTempMax(Double tempMax) {
this.tempMax = tempMax;
}
public Double getPressure() {
return pressure;
}
public void setPressure(Double pressure) {
this.pressure = pressure;
}
public Double getSeaLevel() {
return seaLevel;
}
public void setSeaLevel(Double seaLevel) {
this.seaLevel = seaLevel;
}
public Double getGrndLevel() {
return grndLevel;
}
public void setGrndLevel(Double grndLevel) {
this.grndLevel = grndLevel;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public Integer getTempKf() {
return tempKf;
}
public void setTempKf(Integer tempKf) {
this.tempKf = tempKf;
}
}
public class Weather {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("main")
#Expose
private String main;
#SerializedName("description")
#Expose
private String description;
#SerializedName("icon")
#Expose
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
I've been searching online and on here and I have been unable to find how exactly to use GSON with my code which is:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_weather_app, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL));
requestJsonObject();
return view;
}
private void requestJsonObject (){
}
How exactly do I add the GSON parsing to my code? I only need the temperature, max, min, weather and humidity?
EDIT:
Here is some more info. I plan on using a normal http connection with an apikey to get my information. I am also planning on using RecyclerView and here is that code:
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.CurrentRecycler> {
List<Weather> mCurrentWeatherDataList;
public static class CurrentRecycler extends RecyclerView.ViewHolder{
public TextView location;
public TextView currentTemp;
public TextView currentHumidity;
public TextView currentDescription;
public ImageView currentIcon;
public CurrentRecycler (View view) {
super (view);
location = (TextView) view.findViewById(R.id.current_city_location);
currentTemp = (TextView) view.findViewById(R.id.current_temperature);
currentHumidity = (TextView) view.findViewById(R.id.current_humidity);
currentDescription = (TextView) view.findViewById(R.id.current_weather_description);
currentIcon = (ImageView) view.findViewById(R.id.current_weather_icon);
}
}
public RecyclerViewAdapter (List<Weather> mCurrentWeatherDataList) {
this.mCurrentWeatherDataList = mCurrentWeatherDataList;
}
#Override
public CurrentRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final CurrentRecycler currentRecycler = new CurrentRecycler(view);
return currentRecycler;
}
#Override
public void onBindViewHolder( CurrentRecycler holder, int position) {
final Weather currentRecycler = mCurrentWeatherDataList.get(position);
holder.location.setText(currentRecycler.getDefaultLocation());
holder.currentTemp.setText((currentRecycler.getDefaultCurrentTemp()));
holder.currentHumidity.setText(currentRecycler.getDefaultHumidity());
holder.currentDescription.setText(currentRecycler.getDefaultDescription());
}
#Override
public int getItemCount() {
return mCurrentWeatherDataList.size();
}
}
In your requestJsonObject method, use volley or okhttp to fetch the weather data from API.
Once you get the data as a String, you can use the following code:
List list = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(str, List.class);
Main main = list.getDt();
main.getTemp();
main.getTempMin();
main.getTempMax();
str means your api response data. List means your first entity class.
Moreover, I strongly recommend you to rename your class name, never try to use the reserved name of Java, make them meaningful.