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)
Related
I created basic android screen with listing popular movies(THE MOVIE DB)enter code here.I am using recyclerview to do this.When I click up the movie,I see the details about that film.Everything is okey until the here.My main purpose is uploading the movie poster in firebase.My connection has been done.I can write movie name,rating and overview but I can't upload the movie poster in firebase.Are there any person that can help me? Thank you
public class MyMovieAdapter extends RecyclerView.Adapter<MyMovieAdapter.MyViewHolder> {
private Context context;
private List<Movie> mList;
public static String movieId;
public Glide x;
private DatabaseReference dRef= FirebaseDatabase.getInstance().getReference();
private DatabaseReference rootRef=dRef.child("user");
private StorageReference storageManager;
public MyMovieAdapter(Context context, List<Movie> mList) {
this.context = context;
this.mList = mList;
}
#NonNull
#Override
public MyMovieAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).
inflate(R.layout.movie_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyMovieAdapter.MyViewHolder holder, int position) { //final
holder.title.setText(mList.get(position).getTitle());
String vote=Double.toString(mList.get(position).getVoteAverage());
holder.uservote.setText(vote);
Glide.with(context).load(mList.get(position).getImagePath()).into(holder.image);//placeholder?
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView title,uservote;
public ImageView image;
MyViewHolder(View view){
super(view);
title=view.findViewById(R.id.movie_title);
uservote=view.findViewById(R.id.movie_rate);
image=view.findViewById(R.id.movie_image_2);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos=getAdapterPosition();
//if line
Movie selectedMovie=mList.get(pos);
Intent i=new Intent(context,DetailActivity.class);
i.putExtra("original_title",mList.get(pos).getTitle());
i.putExtra("poster_path",mList.get(pos).getImagePath());
i.putExtra("overview",mList.get(pos).getOverView());
i.putExtra("vote_average",Double.toString(mList.get(pos).getVoteAverage()));
i.putExtra("release_date",mList.get(pos).getReleaseDate());
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
movieId=dRef.push().getKey();
rootRef.child(movieId).child("movieName").setValue(mList.get(pos).getTitle());
rootRef.child(movieId).child("movieImage").setValue(mList.get(pos).getImagePath());
//storageManager.child(mList.get(pos).getImagePath());
storageManager=FirebaseStorage.getInstance().getReference();
Uri u=Uri.parse(mList.get(pos).getImagePath());
storageManager.putFile(u).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
});
context.startActivity(i);
}
});
}
}
}
public class DetailActivity extends AppCompatActivity {
public TextView movieName,movieOverView,movieReleaseDate,movieUserAverage;
public ImageView imageView;
private Uri imageUri;
private DatabaseReference dRef= FirebaseDatabase.getInstance().getReference();
private DatabaseReference rootRef=dRef.child("user");
private StorageReference storageManager= FirebaseStorage.getInstance().getReference("upload").child("eee");
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_content_detail_layout);
imageView=findViewById(R.id.movie_image);
movieName=findViewById(R.id.movie_name);
movieOverView=findViewById(R.id.movie_overview);
movieReleaseDate=findViewById(R.id.movie_release_date);
movieUserAverage=findViewById(R.id.movie_vote_average);
Intent comenIntent=getIntent();
if(comenIntent.hasExtra("original_title")){
String nameOfMovie=getIntent().getExtras().getString("original_title");
String overView=getIntent().getExtras().getString("overview");
String vote=getIntent().getExtras().getString("vote_average");
String releaseDate=getIntent().getExtras().getString("release_date");
String image=getIntent().getExtras().getString("poster_path");
Glide.with(this).load(image).into(imageView);
movieName.setText(nameOfMovie);
movieOverView.setText(overView);
movieUserAverage.setText(vote);
movieReleaseDate.setText(releaseDate);
//StorageReference st=storageManager.child("fff");
//selectImage();
imageUri=Uri.parse(image);
//getFileExtension(imageUri);
storageManager.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
}
private void selectImage(){
Intent b=new Intent();
b.setType("image/*");
b.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(b,RESULT_OK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
imageUri=data.getData();
}
}
private String getFileExtension(Uri uri){
ContentResolver cR=getContentResolver();
MimeTypeMap mime=MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
}
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyMovieAdapter myMovieAdapter;
private ArrayList<Movie> movieList;
private SwipeRefreshLayout swipeRefreshLayout;
public ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editScreen();
swipeRefreshLayout=findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_orange_dark);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
editScreen();
Toast.makeText(MainActivity.this,"Movies Refreshed",Toast.LENGTH_SHORT).show();
}
});
}
public Activity getActivity(){
Context context=this;
while (context instanceof ContextWrapper){
if (context instanceof Activity){
return (Activity) context;
}
context=((ContextWrapper)context).getBaseContext();
}
return null;
}
private void editScreen(){
progressDialog=new ProgressDialog(this);
progressDialog.setMessage("Movies are being refreshed !");
progressDialog.setCancelable(false);
progressDialog.show();
recyclerView=findViewById(R.id.recycler_view);
movieList=new ArrayList<>();
myMovieAdapter=new MyMovieAdapter(this,movieList);
//recyclerView.setHasFixedSize(true);
//RecyclerView.LayoutManager lm=new LinearLayoutManager(getApplicationContext());
//recyclerView.setLayoutManager(lm);
//recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(),LinearLayoutManager.VERTICAL));
if(getActivity().getResources().getConfiguration().orientation== Configuration.ORIENTATION_PORTRAIT){
recyclerView.setLayoutManager(new GridLayoutManager(this,1));
}else{
recyclerView.setLayoutManager(new GridLayoutManager(this,4));
}
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(myMovieAdapter);
myMovieAdapter.notifyDataSetChanged();
loadJSON();
}
private void loadJSON(){
try{
if (BuildConfig.THE_MOVIE_DB_API_KEY.isEmpty()){
Toast.makeText(getApplicationContext(),"Empty API KEY",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
return;
}
Client client=new Client();
Service apiService=client.getClient().create(Service.class);
Call <MovieGetting> call=apiService.getPopularMovies(BuildConfig.THE_MOVIE_DB_API_KEY);
call.enqueue(new Callback<MovieGetting>() {
#Override
public void onResponse(Call<MovieGetting> call, Response<MovieGetting> response) {
// Log.v("RESPONSE_CALLED", "ON_RESPONSE_CALLED");
List<Movie> movies=response.body().getResults();
//if(response.body().getResults()==null){
// Log.v("RESPONSE_CALLED", "ON_RESPONSE_NULL");
// }
recyclerView.setAdapter(new MyMovieAdapter(getApplicationContext(),movies));
recyclerView.smoothScrollToPosition(0);
if (swipeRefreshLayout.isRefreshing()){
swipeRefreshLayout.setRefreshing(false);
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<MovieGetting> call, Throwable t) {
Toast.makeText(getApplicationContext(),"Empty API KEY",Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e){
Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.androidSettings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void selectImage(){
Intent b=new Intent();
b.setType("image/*");
b.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(b,RESULT_OK);
}
}
public class Client {
public static final String BASE_URL="https://api.themoviedb.org/3/";
public static Retrofit retrofit=null;
public static Retrofit getClient(){
if (retrofit==null){
retrofit=new Retrofit.Builder().
baseUrl(BASE_URL).
addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
public interface Service {
#GET("movie/popular")
Call<MovieGetting> getPopularMovies(#Query("api_key") String apiKey);
}
public class Movie {
#SerializedName("id")
private Integer id;
#SerializedName("title")
private String title;
#SerializedName("overview")
private String overView;
#SerializedName("release_date")
private String releaseDate;
#SerializedName("vote_count")
private Integer voteCount;
#SerializedName("poster_path")
private String imagePath;
#SerializedName("adult")
private Boolean adult;
#SerializedName("video")
private Boolean video;
#SerializedName("genre_ids")
private List<Integer>genreIds=new ArrayList<Integer>();
#SerializedName("vote_average")
private Double voteAverage;
#SerializedName("popularity")
private Double popularity;
#SerializedName("original_language")
private String originalLanguage;
#SerializedName("original_title")
private String originalTitle;
#SerializedName("backdrop_path")
private String backdropPath;
public String staticUrl="https://image.tmdb.org/t/p/w500";
public Movie(Integer id, String title, String overView, String releaseDate, Integer voteCount,
String imagePath, Boolean adult, Boolean video, List<Integer> genreIds, Double voteAverage,
Double popularity, String originalLanguage, String originalTitle, String backdropPath) {
this.id = id;
this.title = title;
this.overView = overView;
this.releaseDate = releaseDate;
this.voteCount = voteCount;
this.imagePath = imagePath;
this.adult = adult;
this.video = video;
this.genreIds = genreIds;
this.voteAverage = voteAverage;
this.popularity = popularity;
this.originalLanguage = originalLanguage;
this.originalTitle = originalTitle;
this.backdropPath = backdropPath;
}
public Boolean getAdult() {
return adult;
}
public void setAdult(Boolean adult) {
this.adult = adult;
}
public Boolean getVideo() {
return video;
}
public void setVideo(Boolean video) {
this.video = video;
}
public List<Integer> getGenreIds() {
return genreIds;
}
public void setGenreIds(List<Integer> genreIds) {
this.genreIds = genreIds;
}
public Double getVoteAverage() {
return voteAverage;
}
public void setVoteAverage(Double voteAverage) {
this.voteAverage = voteAverage;
}
public Double getPopularity() {
return popularity;
}
public void setPopularity(Double popularity) {
this.popularity = popularity;
}
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 String getBackdropPath() {
return backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
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 getOverView() {
return overView;
}
public void setOverView(String overView) {
this.overView = overView;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public int getVoteCount() {
return voteCount;
}
public void setVoteCount(int voteCount) {
this.voteCount = voteCount;
}
public String getImagePath() {
return "https://image.tmdb.org/t/p/w185"+imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
public class MovieGetting {
#SerializedName("page")
#Expose
private int page;
#SerializedName("results")
#Expose
private List<Movie> results;
#SerializedName("total_results")
#Expose
private int totalResults;
#SerializedName("total_pages")
#Expose
private int totalPages;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public List<Movie> getResults() {
return results;
}
public void setResults(List<Movie> results) {
this.results = results;
}
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;
}
}
THIS MY ERRORS
E/UploadTask: could not locate file for uploading:https://image.tmdb.org/t/p/w185/AkJQpZp9WoNdj7pLYSj1L0RcMMN.jpg
E/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
E/StorageException: No content provider: https://image.tmdb.org/t/p/w185/AkJQpZp9WoNdj7pLYSj1L0RcMMN.jpg
java.io.FileNotFoundException: No content provider: https://image.tmdb.org/t/p/w185/AkJQpZp9WoNdj7pLYSj1L0RcMMN.jpg
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1435)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1286)
at android.content.ContentResolver.openInputStream(ContentResolver.java:1006)
at com.google.firebase.storage.UploadTask.(Unknown Source:156)
at com.google.firebase.storage.StorageReference.putFile(Unknown Source:13)
at com.example.enes.cinemaapp.MyMovieAdapter$MyViewHolder$1.onClick(MyMovieAdapter.java:110)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25883)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6642)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
E/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
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.
I know guys. Null pointer was already a lot. Honestly, I read all that topics but I can't find a mistake in the code. Please help.
I use regular scheme RxJava + retrofit but got null pointer logs says that mistake in response. Might be problem in model but I checked it. I know I lost something but can't find out what exactly.
Fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/**
* Main Initialization
*/
resultsList = new ArrayList<>();
//adapter = new ListAdapter(resultsList);
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);
/**
* Checking for internet connection
*/
if (InternetConnection.checkConnection(getContext())) {
final ProgressDialog dialog;
dialog = new ProgressDialog(getContext());
dialog.setTitle(getString(R.string.string_getting_json_title));
dialog.setMessage(getString(R.string.string_getting_json_message));
dialog.show();
/**
* Making HTTP request
*/
ApiService api = RetrofitClient.getApiService();
Observable.just(api.getPhotosList(getString(R.string.api_key)))
.map(Call::execute)
.filter(Response::isSuccessful)
.map(Response::body)
.onErrorReturn(throwable -> new ResultsPojo(new ArrayList<>(), 1))
.doOnError(throwable -> Log.e("ERROR", throwable.getMessage()))
.map(ResultsPojo::getMovies)
.doOnNext(list -> {
if (!list.isEmpty()) {
adapter = new ListAdapter(list);
recyclerView.setAdapter(adapter);
} else Log.d("LISTMOVIES", "Something went wrong!!!");
}).subscribe();
ApiService
public interface ApiService {
#GET("3/movie/popular")
Call<ResultsPojo> getPhotosList(#Query("api_key") String key);
}
MoviesPojo
public class MoviesPojo {
#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;
}
}
ResultsPojo
public class ResultsPojo {
#SerializedName("page")
#Expose
private int page;
#SerializedName("total_results")
#Expose
private int totalResults;
#SerializedName("total_pages")
#Expose
private int totalPages;
#SerializedName("moviesPojos")
#Expose
private List<MoviesPojo> moviesPojos;
public ResultsPojo(List<MoviesPojo> results, int page){
this.moviesPojos = 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 List<MoviesPojo> getMovies() {
return moviesPojos;
}
public void setMoviesPojos(List<MoviesPojo> moviesPojos) {
this.moviesPojos = moviesPojos;
}
}
Adapter
private List<MoviesPojo> resultList;
private ItemClickListener mClickListener;
public ListAdapter(List<MoviesPojo> data) {
this.resultList = data;
}
#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) {
}
#Override
public int getItemCount() {
//TODO Здесь мы должны получить список ссылок для изображений
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);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
// public String getItem(int id) {
// return resultList.get(id);
// }
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener {
void onItemClick(View view, int position);
}
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.borisruzanov.popularmovies, PID: 10947
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.borisruzanov.popularmovies/com.borisruzanov.popularmovies.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.borisruzanov.popularmovies.adapters.ListAdapter.setClickListener(com.borisruzanov.popularmovies.adapters.ListAdapter$ItemClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.borisruzanov.popularmovies.adapters.ListAdapter.setClickListener(com.borisruzanov.popularmovies.adapters.ListAdapter$ItemClickListener)' on a null object reference
at com.borisruzanov.popularmovies.ListFragment.onCreateView(ListFragment.java:51)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2346)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3248)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3200)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:195)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:597)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1248)
at android.app.Activity.performStart(Activity.java:6679)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2609
Thank you very much for your time!!! +1 to karma
getitemcount() return null in RecyclerView adapter. When I run my app, it crashes and the error message is movies item size in getitemcount() returns null.
Here's the relevant code:
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder>
{
private Context context;
private List<Movie> movieList;
public MoviesAdapter(Context context, List<Movie> movieList) {
this.context = context;
this.movieList = movieList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_card,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.title.setText(movieList.get(position).getOriginal_title());
String vote = Double.toString(movieList.get(position).getVoteAverage());
holder.userrating.setText(vote);
Glide.with(context).load(movieList.get(position).getPosterpath()).placeholder(R.drawable.loading).into(holder.imageView);
}
#Override
public int getItemCount() {
return movieList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
private TextView title,userrating;
private ImageView imageView;
public MyViewHolder(final View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.movietitle);
userrating = (TextView) itemView.findViewById(R.id.userrating);
imageView = (ImageView) itemView.findViewById(R.id.thumbnail);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION)
{
Movie clickedDataItem = movieList.get(pos);
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("original_title" , movieList.get(pos).getOriginal_title());
intent.putExtra("poster",movieList.get(pos).getPosterpath());
intent.putExtra("overview",movieList.get(pos).getOverview());
intent.putExtra("vot_average",movieList.get(pos).getVote_count());
intent.putExtra("release_date",movieList.get(pos).getRelease_data());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Toast.makeText(view.getContext(),"you clicked "+clickedDataItem.getOriginal_title(),Toast.LENGTH_LONG).show();
}
}
});
}
}
}
public interface Service {
#GET("/3/movie/popular")
Call<MoviesResponse> getPopularMovies (#Query("api_key") String apikey);
}
public class MoviesResponse {
private int page;
private List <Movie> result;
private int totalresult;
private int totalpage;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public List<Movie> getResult() {
return result;
}
public void setResult(List<Movie> result) {
this.result = result;
}
public int getTotalresult() {
return totalresult;
}
public void setTotalresult(int totalresult) {
this.totalresult = totalresult;
}
public int getTotalpage() {
return totalpage;
}
public void setTotalpage(int totalpage) {
this.totalpage = totalpage;
}
}
public class Movie {
private String posterpath;
private boolean adult;
private String overview;
private String release_data;
private List<Integer> genre_ids = new ArrayList<Integer>();
private int id;
private String original_title;
private String original_language;
private String title;
private String backdroppath;
private Double popularity;
private int vote_count;
private boolean video;
private Double voteAverage;
public Movie(String posterpath, boolean adult, String overview, String release_data, List<Integer> genre_ids, int id, String original_title, String original_language, String title, String backdroppath, Double popularity, int vote_count, boolean video, Double voteAverage) {
this.posterpath = posterpath;
this.adult = adult;
this.overview = overview;
this.release_data = release_data;
this.genre_ids = genre_ids;
this.id = id;
this.original_title = original_title;
this.original_language = original_language;
this.title = title;
this.backdroppath = backdroppath;
this.popularity = popularity;
this.vote_count = vote_count;
this.video = video;
this.voteAverage = voteAverage;
}
String baseImageUrl = "https://image.tmdb.org/t/p/w500";
public String getPosterpath() {
return "https://image.tmdb.org/t/p/w500" + posterpath;
}
public void setPosterpath(String posterpath) {
this.posterpath = posterpath;
}
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 getRelease_data() {
return release_data;
}
public void setRelease_data(String release_data) {
this.release_data = release_data;
}
public List<Integer> getGenre_ids() {
return genre_ids;
}
public void setGenre_ids(List<Integer> genre_ids) {
this.genre_ids = genre_ids;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOriginal_title() {
return original_title;
}
public void setOriginal_title(String original_title) {
this.original_title = original_title;
}
public String getOriginal_language() {
return original_language;
}
public void setOriginal_language(String original_language) {
this.original_language = original_language;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBackdroppath() {
return backdroppath;
}
public void setBackdroppath(String backdroppath) {
this.backdroppath = backdroppath;
}
public Double getPopularity() {
return popularity;
}
public void setPopularity(Double popularity) {
this.popularity = popularity;
}
public int getVote_count() {
return vote_count;
}
public void setVote_count(int vote_count) {
this.vote_count = vote_count;
}
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 getBaseImageUrl() {
return baseImageUrl;
}
public void setBaseImageUrl(String baseImageUrl) {
this.baseImageUrl = baseImageUrl;
}
}
public class Client {
public static final String BASE_URL = "https://api.themoviedb.org";
public static final String API_KEY = "5c723cbb6a71ce839dc704a80febe3fb";
public static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MoviesAdapter adapter;
private List<Movie> movieList;
ProgressDialog pd;
private TextView textView;
private SwipeRefreshLayout swipecontainer;
public static final String LOG_TAG = MoviesAdapter.class.getName();
#SuppressLint("ResourceAsColor")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initview();
swipecontainer = (SwipeRefreshLayout) findViewById(R.id.main_content);
swipecontainer.setColorSchemeColors(android.R.color.holo_orange_dark);
swipecontainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
initview();
Toast.makeText(MainActivity.this,"Movies Refreshed",Toast.LENGTH_LONG).show();
}
});
}
public Activity getActivity ()
{
Context context =this;
while (context instanceof ContextWrapper)
{
return (Activity) context;
}
context =((ContextWrapper) context).getBaseContext();
return null;
}
private void initview() {
pd = new ProgressDialog(this);
pd.setMessage("Fetching Movies");
pd.setCancelable(false);
pd.show();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
movieList = new ArrayList<>();
adapter = new MoviesAdapter(this,movieList);
if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
recyclerView.setLayoutManager(new GridLayoutManager(this,2));
}
else
{
recyclerView.setLayoutManager(new GridLayoutManager(this,4) );
}
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
loadjson();
}
private void loadjson() {
try {
if(BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty())
{
Toast.makeText(getApplicationContext(),"please obtain API key",Toast.LENGTH_LONG).show();
return;
}
Client client= new Client();
Service apiservice = Client.getClient().create(Service.class);
Call<MoviesResponse> call = apiservice.getPopularMovies("5c723cbb6a71ce839dc704a80febe3fb");
call.enqueue(new Callback<MoviesResponse>() {
#Override
public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) {
List<Movie> movies = response.body().getResult();
recyclerView.setAdapter(new MoviesAdapter(getApplicationContext(),response.body().getResult()));
recyclerView.smoothScrollToPosition(0);
if (swipecontainer.isRefreshing()) {
swipecontainer.setRefreshing(false);
}
pd.dismiss();
}
#Override
public void onFailure(retrofit2.Call<MoviesResponse> call, Throwable t) {
Log.d("Error" ,t.getMessage());
Toast.makeText(MainActivity.this,"Error Fetching Data! " ,Toast.LENGTH_LONG).show();
}
});
}
catch (Exception e)
{
Log.d("Error" ,e.getMessage());
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.menu_setting :
return true;
default:return super.onOptionsItemSelected(item);
}
}
}
I recently learnt a bit about json parsing with retrofit2. I tried implementing on my own but no output is shown and no errors either in the log cat. What could be wrong? Take a look at my code below:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RestClient restClient;
private List<Movies> moviesList = new ArrayList<>();
private MoviesAdapter adapter;
private final String TAG = MainActivity.class.getCanonicalName();
private RelativeLayout relativeLayout;
private static final String API_KEY = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = (RelativeLayout) findViewById(R.id.activity_main);
if (API_KEY.isEmpty()){
Snackbar.make(relativeLayout, "Access Requires an API Key", Snackbar.LENGTH_LONG);
}
recyclerView = (RecyclerView) findViewById(R.id.rView);
recyclerView.setHasFixedSize(true);
recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MoviesAdapter(MainActivity.this, moviesList, R.layout.movie_items_layout);
recyclerView.setAdapter(adapter);
restClient = new RestClient();
RestEndpoint restService = restClient.getMoviesClient().create(RestEndpoint.class);
Call<MoviesResponse> moviesResponseCall = restService.getTopRatedMovies(API_KEY);
moviesResponseCall.enqueue(new Callback<MoviesResponse>() {
#Override
public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) {
moviesList.clear();
moviesList.addAll(response.body().getMoviesResult());
List<Movies> list = response.body().getMoviesResult();
for (Movies movies : list){
Movies movies1 = new Movies(movies.isAdult(), movies.getOverview(), movies.getReleaseDate(),
movies.getTitle(), movies.getBackdropPath(), movies.getVoteAverage());
}
adapter.notifyDataSetChanged();
//moviesList = response.body().getMoviesResult();
Log.v(TAG, "Number of Movies Received:" + moviesList.size());
}
#Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
}
});
}
}
Movies data model class is shown below:
public class Movies {
#SerializedName("poster_path")
private String posterPath;
#SerializedName("adult")
private boolean adult;
#SerializedName("overview")
private String overview;
#SerializedName("release_date")
private String releaseDate;
#SerializedName("genre_ids")
private List<Integer> genreIds;
#SerializedName("id")
private int id;
#SerializedName("original_title")
private String originalTitle;
#SerializedName("original_language")
private String originalLanguage;
#SerializedName("title")
private String title;
#SerializedName("backdrop_path")
private String backdropPath;
#SerializedName("popularity")
private double popularity;
#SerializedName("vote_count")
private String voteCount;
#SerializedName("video")
private boolean video;
#SerializedName("vote_average")
private double voteAverage;
public Movies(boolean adult, String overview, String releaseDate, String title, String backdropPath, double voteAverage) {
this.adult = adult;
this.overview = overview;
this.releaseDate = releaseDate;
this.title = title;
this.backdropPath = backdropPath;
this.voteAverage = voteAverage;
}
public Movies() {
}
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;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBackdropPath() {
return backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public double getVoteAverage() {
return voteAverage;
}
public void setVoteAverage(double voteAverage) {
this.voteAverage = voteAverage;
}
}
Also take a look at my recyclerview adapter class:
public class MoviesAdapter extends RecyclerView.Adapter<MoviesHolder> {
private Context context;
private List<Movies> moviesList;
private int rowLayout;
public MoviesAdapter(Context context, List<Movies> moviesList, int rowLayout) {
this.context = context;
this.moviesList = moviesList;
this.rowLayout = rowLayout;
}
#Override
public MoviesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mView = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new MoviesHolder(mView);
}
#Override
public void onBindViewHolder(MoviesHolder holder, int position) {
Movies movies = moviesList.get(position);
holder.title.setText(movies.getTitle());
holder.date.setText(movies.getReleaseDate());
holder.desription.setText(movies.getOverview());
holder.rating.setText(String.valueOf(movies.getVoteAverage()));
Picasso.with(context)
.load(movies.getBackdropPath())
.into(holder.backdrop);
}
#Override
public int getItemCount() {
moviesList = new ArrayList<>();
return moviesList.size();
}
}
The json data was fetched from themoviedb website with an api key. Kindly point out what's wrong.
You have a mistake in
#Override
public int getItemCount() {
moviesList = new ArrayList<>();
return moviesList.size();
}
You are creating new list , which size is 0, so your adapter always thinks there are no elememnts
Just try removing moviesList = new ArrayList<>();