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.
Related
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.
Need help. I know how to populate List. But dont know how to make it work with retrofit + recyclerView. I need to populate recycler view with images. Images has to come with help of retrofit and after extracting their link from json they has to be put in image view.
My adapter
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ListViewHolder> {
/**
* General
*/
private List<ResultsPojo> resultList;
private LayoutInflater layoutInflater;
/**
* Garbage
*/
private ItemClickListener mClickListener;
public ListAdapter(List<ResultsPojo> resultList, Context context) {
this.resultList = resultList;
this.layoutInflater = LayoutInflater.from(context);
}
#NonNull
#Override
public ListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_banner, parent, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ListViewHolder holder, int position) {
Context context = holder.mImageBanner.getContext();
ResultsPojo item = resultList.get(position);
Log.d("tag", "on bind view item " + item.toString());
Picasso.get().load(item.getPosterPath()).into(holder.mImageBanner);
}
#Override
public int getItemCount() {
return resultList.size();
}
public class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView mImageBanner;
public ListViewHolder(View itemView) {
super(itemView);
mImageBanner = (ImageView) itemView.findViewById(R.id.item_banner_image);
itemView.setOnClickListener(this);
}
My model
public class BasePojo {
#SerializedName("page")
#Expose
private int page;
#SerializedName("total_results")
#Expose
private int totalResults;
#SerializedName("total_pages")
#Expose
private int totalPages;
#SerializedName("results")
#Expose
private ArrayList<ResultsPojo> results;
public BasePojo(ArrayList<ResultsPojo> results, int page){
this.results = results;
this.page = page;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getTotalResults() {
return totalResults;
}
public void setTotalResults(int totalResults) {
this.totalResults = totalResults;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public ArrayList<ResultsPojo> getResults() {
return results;
}
public void setResults(ArrayList<ResultsPojo> results) {
this.results = results;
}
}
Another model because there is a list and list inside it
public class ResultsPojo {
#SerializedName("vote_count")
#Expose
private int voteCount;
#SerializedName("id")
#Expose
private int id;
#SerializedName("video")
#Expose
private boolean video;
#SerializedName("vote_average")
#Expose
private double voteAverage;
#SerializedName("title")
#Expose
private String title;
#SerializedName("popularity")
#Expose
private double popularity;
#SerializedName("poster_path")
#Expose
private String posterPath;
#SerializedName("original_language")
#Expose
private String originalLanguage;
#SerializedName("original_title")
#Expose
private String originalTitle;
#SerializedName("genre_ids")
#Expose
private List<Integer> genreIds = null;
#SerializedName("backdrop_path")
#Expose
private String backdropPath;
#SerializedName("adult")
#Expose
private boolean adult;
#SerializedName("overview")
#Expose
private String overview;
#SerializedName("release_date")
#Expose
private String releaseDate;
public int getVoteCount() {
return voteCount;
}
public void setVoteCount(int voteCount) {
this.voteCount = voteCount;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isVideo() {
return video;
}
public void setVideo(boolean video) {
this.video = video;
}
public double getVoteAverage() {
return voteAverage;
}
public void setVoteAverage(double voteAverage) {
this.voteAverage = voteAverage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPopularity() {
return popularity;
}
public void setPopularity(double popularity) {
this.popularity = popularity;
}
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}
public String getOriginalTitle() {
return originalTitle;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public List<Integer> getGenreIds() {
return genreIds;
}
public void setGenreIds(List<Integer> genreIds) {
this.genreIds = genreIds;
}
public String getBackdropPath() {
return backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public boolean isAdult() {
return adult;
}
public void setAdult(boolean adult) {
this.adult = adult;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
}
My retrofit client
public class RetrofitClient {
/**
* URLS
**/
private static final String BASE_URL = "http://api.themoviedb.org/";
/**
* Retrofit instance
**/
private static Retrofit getRetrofitInstance(){
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL)
.build();
}
/**
* Api Service
**/
public static ApiService getApiService(){
return getRetrofitInstance().create(ApiService.class);
}
}
Api service
public interface ApiService {
#GET("3/movie/popular")
Call<BasePojo> getPhotosList(#Query("api_key") String key);
}
and my fragment
RecyclerView recyclerView;
View view;
private ArrayList<ResultsPojo> resultsList;
private ListAdapter adapter;
public ListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/**
* Main Initialization
*/
resultsList = new ArrayList<>();
view = inflater.inflate(R.layout.fragment_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_list_detailed);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//adapter.setClickListener(this);
ApiService api = RetrofitClient.getApiService();
Call<BasePojo> call = api.getPhotosList(getString(R.string.api_key));
call.enqueue(new Callback<BasePojo>() {
#Override
public void onResponse(Call<BasePojo> call, Response<BasePojo> response) {
Log.d("tag", "inside on response");
resultsList = response.body().getResults();
adapter = new ListAdapter(resultsList,getContext());
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<BasePojo> call, Throwable t) {
Log.d("tag", "inside failure");
}
});
return view;
}
I think you didn't give us a clear error or problem but I will say what I've done wrong before about Retrofit.
1- Do not forget to add INTERNET permission in Manifest
2- If your response is a list, you should define
Call<List<YourModelHere>> instead of
Call<YourModelHere>
in both Interface and the place where you call.
3- Learn to work in debug-mode if you don't know. So, basically you can understand which response you're retrieving or which you don't.
4- Except these, I always used Picasso&Retrofit like this;
(But I'm sure that you're wrong here, because you should retrieve as position and you can get all posters, in the style you do you can only get one or none)
Picasso.with(context).load(item.get(position).getPosterPath).into(holder.mImageBanner);
(Define Context context in global)
i got data from api link (server) to display data in recyclview ,if i want to click on items then it will open next activity thats fine, but some items have no data , if i want to click geting class cast exception
in this above image, click on Adventure , then it will open next activity with related data , if i want click on Kids Activities then getting Class cast exception error because from server no data is available of Kids Activities ,
if i want click on Kids ACtivities then it wil open toast massage like no more data is available , how should i get it?
This is adapter class
public class SubCategoryChild_Adapter extends RecyclerView.Adapter {
private List<SubCategoryChild> subCategoryChildList;
private Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView
discountName,
subcategorychild_merchantName,
subcategoryChild_discountedPrice,
subcategoryChild_actualPrice,
subcategoryChild_distance,
staticUgx;
public ImageView SubcategoryChild_imageView;
public SubCategoryChild subCategoryChild;
public MyViewHolder(View view) {
super(view);
subcategoryChild_actualPrice = (TextView) view.findViewById(R.id.ScChild_actualPrice);
subcategoryChild_actualPrice.setPaintFlags(subcategoryChild_actualPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
subcategoryChild_discountedPrice = (TextView) view.findViewById(R.id.ScChild_discountedPrice);
subcategorychild_merchantName = (TextView) view.findViewById(R.id.ScChild_merchantName);
staticUgx = (TextView) view.findViewById(R.id.ScChild_actualprice_ugx);
staticUgx.setPaintFlags(staticUgx.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
subcategoryChild_distance = (TextView) view.findViewById(R.id.ScChild_Near_Location_text);
discountName = (TextView) view.findViewById(R.id.ScChild_Discount_Text);
SubcategoryChild_imageView = (ImageView) view.findViewById(R.id.ScChild_imageView);
}
}
public SubCategoryChild_Adapter(Context context , List<SubCategoryChild> subCategoryChildList) {
this.subCategoryChildList = subCategoryChildList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder itemView;
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.subcategorydeal_list, parent, false);
itemView = new MyViewHolder(view);
return itemView;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,int position){
final SubCategoryChild subCategoryChild = subCategoryChildList.get(position);
((MyViewHolder) holder).subcategorychild_merchantName.setText(subCategoryChild.getMerchantName());
((MyViewHolder) holder).discountName.setText(subCategoryChild.getName());
((MyViewHolder) holder).subcategoryChild_actualPrice.setText(subCategoryChild.getActualPrice());
((MyViewHolder) holder).subcategoryChild_discountedPrice.setText(subCategoryChild.getDiscountedPrice());
((MyViewHolder) holder).subcategoryChild_distance.setText(subCategoryChild.getDistance());
context = ((MyViewHolder) holder).SubcategoryChild_imageView.getContext();
Picasso.with(context).load(subCategoryChild.getLogo()).fit().into(((MyViewHolder)holder).SubcategoryChild_imageView);
((MyViewHolder) holder).subCategoryChild = subCategoryChild;
}
#Override
public int getItemCount() {
if(subCategoryChildList == null){
return 0;
}else {
return subCategoryChildList.size();
}
}
}
this is model class
public class SubCategoryChild {
#SerializedName("merchant_id")
#Expose
private String merchantId;
#SerializedName("merchant_name")
#Expose
private String merchantName;
#SerializedName("name")
#Expose
private String name;
#SerializedName("deal_sub_title")
#Expose
private String dealSubTitle;
#SerializedName("discounted_price")
#Expose
private String discountedPrice;
#SerializedName("actual_price")
#Expose
private String actualPrice;
#SerializedName("discounted_percentage")
#Expose
private String discountedPercentage;
#SerializedName("category_id")
#Expose
private String categoryId;
#SerializedName("sub_category_id")
#Expose
private String subCategoryId;
#SerializedName("city_id")
#Expose
private String cityId;
#SerializedName("logo")
#Expose
private String logo;
#SerializedName("website")
#Expose
private String website;
#SerializedName("email")
#Expose
private String email;
#SerializedName("phone")
#Expose
private String phone;
#SerializedName("mobile")
#Expose
private String mobile;
#SerializedName("description")
#Expose
private String description;
#SerializedName("Merchant_address")
#Expose
private String merchantAddress;
#SerializedName("latitude")
#Expose
private String latitude;
#SerializedName("longitude")
#Expose
private String longitude;
#SerializedName("distance")
#Expose
private String distance;
#SerializedName("deal_count")
#Expose
private Integer dealCount;
public String getMerchantId() {
return merchantId;
}
public void setMerchantId(String merchantId) {
this.merchantId = merchantId;
}
public String getMerchantName() {
return merchantName;
}
public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDealSubTitle() {
return dealSubTitle;
}
public void setDealSubTitle(String dealSubTitle) {
this.dealSubTitle = dealSubTitle;
}
public String getDiscountedPrice() {
return discountedPrice;
}
public void setDiscountedPrice(String discountedPrice) {
this.discountedPrice = discountedPrice;
}
public String getActualPrice() {
return actualPrice;
}
public void setActualPrice(String actualPrice) {
this.actualPrice = actualPrice;
}
public String getDiscountedPercentage() {
return discountedPercentage;
}
public void setDiscountedPercentage(String discountedPercentage) {
this.discountedPercentage = discountedPercentage;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getSubCategoryId() {
return subCategoryId;
}
public void setSubCategoryId(String subCategoryId) {
this.subCategoryId = subCategoryId;
}
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMerchantAddress() {
return merchantAddress;
}
public void setMerchantAddress(String merchantAddress) {
this.merchantAddress = merchantAddress;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public Integer getDealCount() {
return dealCount;
}
public void setDealCount(Integer dealCount) {
this.dealCount = dealCount;
}
}
this is activity class
public class SubCategoryChild_Activity extends AppCompatActivity {
RecyclerView subCategoryDeal_RecyclerView;
public Context context;
ProgressBar progress_bar;
SubCategoryChild_Adapter subCategoryChild_adapter;
List<SubCategoryChild> subCategoryChildList;
SubCategoryChild subCategoryChild;
public String catId,subCatId,ActionBar_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_category_child_);
Bundle extras = getIntent().getExtras();
catId = extras.getString("cat_Id");
subCatId = extras.getString("Sub_CatId");
ActionBar_Name = extras.getString("actionBar_Name");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(ActionBar_Name);
subCategoryDeal_RecyclerView = (RecyclerView) findViewById(R.id.subCategoryDeal_RecyclerView);
final ProgressBar progress_bar = (ProgressBar) findViewById(R.id.ScChild_progress_bar);
subCategoryDeal_RecyclerView.setLayoutManager(new LinearLayoutManager(this));
subCategoryDeal_RecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
subCategoryDeal_RecyclerView.setLayoutManager(layoutManager);
subCategoryDeal_RecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
subCategoryDeal_RecyclerView.setItemAnimator(new DefaultItemAnimator());
subCategoryChild_adapter = new SubCategoryChild_Adapter(context, subCategoryChildList);
subCategoryDeal_RecyclerView.setAdapter(subCategoryChild_adapter);
progress_bar.setVisibility(View.VISIBLE);
if(new SubCategoryChild_Response().getStatus() == null){
RestClient.get(this).diskCacheEnable(true).new NetworkTask<Void, SubCategoryChild_Response>(SubCategoryChild_Response.class, Http.GET) {
#Override
protected void onPostExecute(SubCategoryChild_Response subCategoryChild_response) {
super.onPostExecute(subCategoryChild_response);
progress_bar.setVisibility(View.GONE);
if (subCategoryChild_response != null && subCategoryChild_response.getSubCategoryChild() != null & subCategoryChild_response.getSubCategoryChild().size() > 0) {
subCategoryChildList = subCategoryChild_response.getSubCategoryChild();
subCategoryChild_adapter = new SubCategoryChild_Adapter(SubCategoryChild_Activity.this, subCategoryChildList);
subCategoryDeal_RecyclerView.setAdapter(subCategoryChild_adapter);
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "https://api.bargaincry.com/apurl/deal/get_merchantBy_subcat/41187/" + catId + "/" + subCatId + "/latitude~longitude");
}else {
if(new SubCategoryChild_Response().getStatus().isEmpty())
Toast.makeText(SubCategoryChild_Activity.this,"error",Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.navigation_,menu);
//getMenuInflater().inflate(R.menu.navigation_, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
ComponentName cn = new ComponentName(this, SearchResultsActivity.class);
searchView.setSearchableInfo(searchManager.getSearchableInfo(cn));
//searchView.setSubmitButtonEnabled(true);
//searchView.setOnQueryTextListener(MainActivity.this);
searchView.setIconifiedByDefault(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
this is Response class
public class SubCategoryChild_Response {
#SerializedName("status")
#Expose
private String status;
#SerializedName("merchant")
#Expose
private List<SubCategoryChild> subCategoryChildList = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<SubCategoryChild> getSubCategoryChild() {
return subCategoryChildList;
}
public void setSubCategoryChildList(List<SubCategoryChild> subCategoryChildList) {
this.subCategoryChildList = subCategoryChildList;
}
}
this is catLog here
FATAL EXCEPTION: main Process: app.com.BargainCryApp, PID: 28129
java.lang.ClassCastException: java.lang.String cannot be cast to
models.SubCategoryChild_Response at
app.com.BargainCryApp.SubCategoryChild_Activity$1.onPostExecute(SubCategoryChild_Activity.java:69)
at android.os.AsyncTask.finish(AsyncTask.java:665) at
android.os.AsyncTask.-wrap1(AsyncTask.java) at
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:682)
at android.os.Handler.dispatchMessage(Handler.java:111) at
android.os.Looper.loop(Looper.java:207) at
android.app.ActivityThread.main(ActivityThread.java:5769) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:861)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
Before casting object, check instanceOf
if (holder instanceof MyViewHolder) {
MyViewHolder mHolder = (MyViewHolder) holder;
mHolder.subcategorychild_merchantName.setText(subCategoryChild.getMerchantName());
//..........
}
For your question how to avoid ClassCastException, the answer is use 'instanceof'
operator and instanceof returns true then further perform your actions.
if (subCategoryChild_response != null &&
subCategoryChild_response.getSubCategoryChild() != null &&
subCategoryChild_response.getSubCategoryChild() instanceof 'Your Child Class should be here'
subCategoryChild_response.getSubCategoryChild().size() > 0)
Hope this helps you
I want to get data from my localhost with retrofit library. I want to make it so that when I click the button, all TextView will set new value. For example, TextView username will change "developer" in my json file. However, when I clicked the button I guess json returned null because I can not see anything. Can you help me solve this problem?
JSON File :
{"USERS":[{"_id":"587c0346f8469d38a0ea46bf",
"username":"developer",
"name":"Akif",
"surname":"Demirezen",
"tel":"023656565",
"age":"25",
"location_id":{"_id":"587c0346f8469d38a0ea46be",
"il":"istanbul",
"ilce":"cevizlibağ"},
"__v":0}]}
Example.class :
public class Example {
#SerializedName("USERS")
#Expose
private List<USER> uSERS = null;
public List<USER> getUSERS() {
return uSERS;
}
public void setUSERS(List<USER> uSERS) {
this.uSERS = uSERS;
}
}
LocationID Class :
public class LocationId {
#SerializedName("_id")
#Expose
private String id;
#SerializedName("il")
#Expose
private String il;
#SerializedName("ilce")
#Expose
private String ilce;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIl() {
return il;
}
public void setIl(String il) {
this.il = il;
}
public String getIlce() {
return ilce;
}
public void setIlce(String ilce) {
this.ilce = ilce;
}
}
Main Activity Class :
public class MainActivity extends AppCompatActivity {
TextView tid,tusername,tname,tsurname,tage,ttel,tlocationid;
Button butonverilerigoster;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tid = (TextView) findViewById(R.id.t_id);
tusername = (TextView) findViewById(R.id.t_username);
tname = (TextView) findViewById(R.id.t_name);
tsurname = (TextView) findViewById(R.id.t_surname);
tage = (TextView) findViewById(R.id.t_age);
ttel = (TextView) findViewById(R.id.t_tel);
tlocationid = (TextView) findViewById(R.id.t_locationid);
butonverilerigoster = (Button) findViewById(R.id.butonusergetir);
butonverilerigoster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Thread(new Runnable() {
public void run() {
ApiService.Factory.getInstance().getuse().enqueue(new Callback<USER>() {
#Override
public void onResponse(Call<USER> call, Response<USER> response) {
tid.setText(response.body().getId());
tusername.setText(response.body().getUsername());
tname.setText(response.body().getName());
tsurname.setText(response.body().getSurname());
tage.setText(response.body().getAge());
ttel.setText(response.body().getTel());
tlocationid.setText((CharSequence) response.body().getLocationId());
}
#Override
public void onFailure(Call<USER> call, Throwable t) {
Log.e("Failed", t.getMessage());
}
});
}
}).start();
}
});
}
}
User class :
public class USER {
#SerializedName("_id")
#Expose
private String id;
#SerializedName("username")
#Expose
private String username;
#SerializedName("name")
#Expose
private String name;
#SerializedName("surname")
#Expose
private String surname;
#SerializedName("tel")
#Expose
private String tel;
#SerializedName("age")
#Expose
private String age;
#SerializedName("location_id")
#Expose
private LocationId locationId;
#SerializedName("__v")
#Expose
private Integer v;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public LocationId getLocationId() {
return locationId;
}
public void setLocationId(LocationId locationId) {
this.locationId = locationId;
}
public Integer getV() {
return v;
}
public void setV(Integer v) {
this.v = v;
}
}