I have problem with adapter. I'm using retrofit 2 to parse JSON data. JSON example, models and adapter code are below.
JSON example:
[{
"id":1,
"type":"TEMPERATURE",
"measurements":[
{
"value":"22.58",
"time":"2017-01-11T12:20:44.701"
}]
},{
"id":2,
"type":"HUMIDITY",
"measurements":[
{
"value":"52.366",
"time":"2017-01-11T12:20:44.731"
}]
},{
"id":3,
"type":"LUMINOSITY",
"measurements":[
{
"value":"1.0",
"time":"2017-01-11T12:20:44.742"
}]
}]
Model Senzori:
public class Senzori {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("type")
#Expose
private String type;
#SerializedName("measurements")
#Expose
private List<Measurement> measurements = new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Measurement> getMeasurements() {
return measurements;
}
public void setMeasurements(List<Measurement> measurements) {
this.measurements = measurements;
}
}
Model Measurement:
public class Measurement {
#SerializedName("value")
#Expose
private String value;
#SerializedName("time")
#Expose
private String time;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
Adapter:
public class SenzoriAdapter extends RecyclerView.Adapter<SenzoriAdapter.Holder>{
private List<Senzori> mSenzori;
public SenzoriAdapter(){
mSenzori = new ArrayList<>();
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_item, parent, false);
return new Holder(row);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
Senzori curr = mSenzori.get(position);
holder.senzoriType.setText(curr.getType());
holder.senzoriLastAlive.setText(curr.getMeasurements().getTime());
holder.senzoriMeasurement.setText(curr.getMeasurements().getValue());
}
#Override
public int getItemCount() {
return mSenzori.size();
}
public void addSenzori(Senzori senzori) {
mSenzori.add(senzori);
notifyDataSetChanged();
}
public class Holder extends RecyclerView.ViewHolder {
private TextView senzoriType, senzoriLastAlive, senzoriMeasurement;
public Holder(View itemView) {
super(itemView);
senzoriType = (TextView) itemView.findViewById(R.id.senzoriType);
senzoriLastAlive = (TextView) itemView.findViewById(R.id.senzoriLastAlive);
senzoriMeasurement = (TextView) itemView.findViewById(R.id.senzoriMeasurement);
}
}
}
I'm getting "Cannot resolve method" on getTime() and getValue().
Since getMeasurements() returns a List and the JSON you have shown contains only one item. Hence you should call it like this:
holder.senzoriLastAlive.setText(curr.getMeasurements().get(0).getTime());
holder.senzoriMeasurement.setText(curr.getMeasurements().get(0).getValue());
I would suggest adding a check to see if getMeasurements() is not empty, else you will get an Exception.
The problem is you haven't given any information on what item from the List that you wish to find the value or time of.
holder.senzoriMeasurement.setText(curr.getMeasurements().get(<item you wish to get>).getValue;
If you want to get the first item in the List
holder.senzoriMeasurement.setText(curr.getMeasurements().get(0).getValue;
Related
i receive NPE when i want to show pics in picasso,
pay attention that i've another adapter which i used picasso,
but in my new adapter this npe error for boolean happens,
and my friends used this code and it performed well,
here is the code that error says
public boolean isVideoNews() {
return !image.isEmpty() && !video.isEmpty() ;
}
and the part that is related to this code in my adapter
videoIndicator.setVisibility(news.isVideoNews() ? View.VISIBLE : View.GONE);
my adapter
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private List<News> newsList;
public NewsAdapter(List<News> newsList) {
this.newsList = newsList;
}
#Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new NewsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false));
}
#Override
public void onBindViewHolder(NewsViewHolder holder, int position) {
holder.bindNews(newsList.get(position));
}
#Override
public int getItemCount() {
return newsList.size();
}
class NewsViewHolder extends RecyclerView.ViewHolder {
private ImageView newsImageView;
private TextView titleTextView;
private TextView dateTextView;
private View videoIndicator;
public NewsViewHolder(View itemView) {
super(itemView);
newsImageView = itemView.findViewById(R.id.iv_news_image);
videoIndicator = itemView.findViewById(R.id.iv_news_VideoIndicator);
titleTextView = itemView.findViewById(R.id.tv_news_title);
dateTextView = itemView.findViewById(R.id.tv_news_date);
}
public void bindNews(News news) {
Picasso.get().load(news.getImage()).into(newsImageView);
videoIndicator.setVisibility(news.isVideoNews() ? View.VISIBLE : View.GONE);
titleTextView.setText(news.getTitle());
dateTextView.setText(news.getDate());
}
}
}
and this is my data model
public class News {
private int id;
private String title;
private String content;
private String date;
private String image;
private String video;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public boolean isVideoNews() {
return !image.isEmpty() && !video.isEmpty() ;
}
}
Error
FATAL EXCEPTION: main
Process: com.example.melal.newsapp, PID: 5958
java.lang.IllegalArgumentException: Path must not be empty.
at com.squareup.picasso.Picasso.load(Picasso.java:332)
at com.example.melal.newsapp.home.NewsAdapter$NewsViewHolder.bindNews(NewsAdapter.java:53)
at com.example.melal.newsapp.home.NewsAdapter.onBindViewHolder(NewsAdapter.java:31)
at com.example.melal.newsapp.home.NewsAdapter.onBindViewHolder(NewsAdapter.java:17)
FATAL EXCEPTION: main
Process: com.example.melal.newsapp, PID: 9523
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference
at com.example.melal.newsapp.data.News.isVideoNews(News.java:60)
at com.example.melal.newsapp.home.NewsAdapter$NewsViewHolder.bindNews(NewsAdapter.java:53)
at com.example.melal.newsapp.home.NewsAdapter.onBindViewHolder(NewsAdapter.java:30)
at com.example.melal.newsapp.home.NewsAdapter.onBindViewHolder(NewsAdapter.java:16)
I get every data when I debug and my texts and title and every things show on UI but just my image does not show,my banners pic show in my another adapter on UI but main problem is the adapter that i told,
please help me
You have to check here null and empty values for path of Image.
Put following line in if condition like:
if(TextUtils.isEmpty(news.getImage())) {
// Load default image
newsImageView.setImageResource(R.drawable.placeholder);
} else {
Picasso.get().load(news.getImage()).into(newsImageView);
}
Hope it will work.
You need to provide seralized name and expose that field of Model class so that your gson can parse it. Currently you have not set it to any field and thus GSON is not parsing your response accordingly. Below is sample code for how to define it in class. You need to expose all your class fields accordingly.
#SerializedName("foo") //name inside quotes must match with your json field name.
#Expose
private String foo;
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 have 2 applications(different package names) which use one Firebase database. One app has to write access to the database and another have read access to the database.in my second application, i use recyclerview to retrieve data which is stored by 1st App.
for this I use below code:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:567....259c8f58311") // Required for Analytics.
.setApiKey("AIzaSyA9BRxl......hE03y5qD-c") // Required for Auth.
.setDatabaseUrl("https://mycity-3a561.firebaseio.com/") // Required for RTDB.
.build();
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
// Get the database for the other app.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
DatabaseReference data = secondaryDatabase.getInstance().getReference();
data.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
WaterClass waterClass = dSnapshot.getValue(WaterClass.class);
Log.d("Show", waterClass.getName() == null ? "" : waterClass.getName());
list.add(waterClass);
}
adapter = new WaterAdapter(ShowWaterDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
Adapter class
private class WaterAdapter extends RecyclerView.Adapter<WaterAdapter.ViewHolder> {
ShowWaterDetails showDetail;
List<WaterClass> listData;
public WaterAdapter(ShowWaterDetails showWaterDetails, List<WaterClass> list) {
this.showDetail = showWaterDetails;
this.listData = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
WaterAdapter.ViewHolder viewHolder = new WaterAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(WaterAdapter.ViewHolder holder, int position) {
WaterClass AllDetails = listData.get(position);
holder.NameTextView.setText(AllDetails.getName());
holder.DetailTextView.setText(AllDetails.getDetail());
holder.DateTextView.setText(AllDetails.getDate());
holder.LocationTextView.setText(AllDetails.getLocation());
holder.TypeTextView.setText(AllDetails.getType());
Picasso.with(showDetail).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);
}
#Override
public int getItemCount() {
return listData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView NameTextView;
public TextView DetailTextView;
public TextView DateTextView;
public TextView LocationTextView;
public TextView TypeTextView;
public ImageView ImageTextView;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = itemView.findViewById(R.id.ShowNameTextView);
DetailTextView = itemView.findViewById(R.id.ShowDetailTextView);
DateTextView = itemView.findViewById(R.id.ShowDateTextView);
LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
ImageTextView = itemView.findViewById(R.id.ShowImageView);
}
}
}
}
POJO Class
class WaterClass {
private String id;
private String email;
private String name;
private String type;
private String detail;
private String location;
private String date;
private String imgurl;
public WaterClass(){
}
public WaterClass(String id, String currentUserString, String imageUrl, String nameString, String typeString, String detailString, String locationString, String dateString) {
this.id = id;
this.email = currentUserString;
this.name =nameString;
this.type = typeString;
this.detail = detailString;
this.location = locationString;
this.date = dateString;
this.imgurl = imageUrl;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
:
there is no error but my recycler not showing anything
go to onStart() and start listening
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
and in your onStop
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
The FirebaseRecyclerAdapter uses a snapshot listener to monitor changes to the Firestore query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
Be sure that the names of constant in the POJO match exatly the names
of your database structure in your firebase console !!
ps: do not post your api-keys or app-ids in your questions, keep them secret, and consider using firebaserecycleradapter if you are using firebase-database , it will be more easy to setup and to show values.
Your POJO is ok !
Found Solution!!
just change this part of a code
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
TO
FirebaseApp.initializeApp(this);
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");
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();
}
I'm new to Android networking. I'm unable to figure out why I'm getting null value for the phonone
This is a sample of JSON data:
{
"columns":{ <some data here> },
"rows":[
{
"timestamp":"28/08/2016 14:11:46",
"name":"Mohammed Sohail",
"phoneno.":8142629002,
"event-name":"Roadies",
"branch":"IT",
"year":3
},
{
"timestamp":"28/08/2016 14:13:03",
"name":"Shaik Asaduddin",
"phoneno.":8143026049,
"event-name":"Ted talk",
"branch":"IT",
"year":3
}
}
I'm able to get every value inside row array except "phoneno" it gives me null value
Here are my classes
Registration class:
public class Registration {
private Columns columns;
private List<Row> rows = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public Columns getColumns() {
return columns;
}
public void setColumns(Columns columns) {
this.columns = columns;
}
public List<Row> getRows() {
return rows;
}
public void setRows(List<Row> rows) {
this.rows = rows;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Row class:
public class Row {
private String timestamp;
private String name;
private String phoneno;
private String eventName;
private String branch;
private String year;
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneno() {
return phoneno;
}
public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
and here is the adapter I'm using to set the text view's
public class RegistrationAdapter extends RecyclerView.Adapter<RegistrationAdapter.RegistrationViewHolder> {
private List<Row> rows;
private Context context;
private int rowLayout;
public RegistrationAdapter(List<Row> rows) {
this.rows=rows;
}
#Override
public RegistrationAdapter.RegistrationViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.registration_item_view, parent, false);
return new RegistrationViewHolder(view);
}
#Override
public void onBindViewHolder(RegistrationViewHolder holder, int position) {
holder.studentName.setText(rows.get(position).getName());
holder.studentPhone.setText(String.valueOf(rows.get(position).getPhoneno()));
holder.studentBranch.setText(rows.get(position).getBranch());
holder.studentYear.setText(rows.get(position).getYear());
}
#Override
public int getItemCount() {
return rows.size();
}
public class RegistrationViewHolder extends RecyclerView.ViewHolder {
LinearLayout studentLayout;
TextView studentName;
TextView studentPhone;
TextView studentBranch;
TextView studentYear;
public RegistrationViewHolder(View itemView) {
super(itemView);
studentLayout=(LinearLayout)itemView.findViewById(R.id.studentLayout);
studentName=(TextView)itemView.findViewById(R.id.studentName);
studentPhone=(TextView)itemView.findViewById(R.id.studentPhoneNumber);
studentBranch=(TextView)itemView.findViewById(R.id.studentBranch);
studentYear=(TextView)itemView.findViewById(R.id.studentYear);
}
}
public RegistrationAdapter( List<Row> rows, int rowLayout,Context context) {
this.rows = rows;
this.rowLayout = rowLayout;
this.context = context;
}
}
Maybe is a typo but in your json you have "phoneno." and your row class specifies phoneno.
you can you use jsonschema2pojo to genenare class from json object.