First of all, Forgive me, my English is not good.
i have a RecyclerView with 9 items, But from the fourth item to the next, Pictures of the first 4 items are repeated for other items!
but other fields For all items in the RecyclerView, Have been completed correctly.
how to fix it problem?
this is my code:
My Model:
public class LocationsListModel {
final String DRAWABLE = "drawable/";
private String name,imageUrl, review, price;
public LocationsListModel(String name, String review, String price, String imageUrl) {
this.name = name;
this.review = review;
this.price = price;
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public String getReview() {
return review;
}
public String getPrice() {
return price;
}
public String getImageUrl() {
return DRAWABLE + imageUrl;
}}
My Adapter:
public class LocationsListAdapter extends RecyclerView.Adapter<LocationsListAdapter.LocationsListView> {
private static ArrayList<LocationsListModel> locationList;
private Context context;
private ImageView locationImage;
public void setItems(ArrayList<LocationsListModel> items) {
this.locationList = items;
}
public class LocationsListView extends RecyclerView.ViewHolder {
public CardView cardView;
public TextView locationName;
public TextView review;
public TextView locationPrice;
public LocationsListView(View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cardView);
locationName = itemView.findViewById(R.id.location_name);
review = itemView.findViewById(R.id.review);
locationPrice = itemView.findViewById(R.id.price);
locationImage = itemView.findViewById(R.id.imageView2);
}
}
#Override
public LocationsListAdapter.LocationsListView onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.locations_list_item, parent, false);
context = parent.getContext();
return new LocationsListView(view);
}
#Override
public void onBindViewHolder(LocationsListAdapter.LocationsListView holder, int position) {
final LocationsListModel locationsListModel = locationList.get(position);
String uri = locationsListModel.getImageUrl();
int resource = locationImage.getResources().getIdentifier(uri, null, locationImage.getContext().getPackageName());
locationImage.setImageResource(resource);
holder.locationName.setText(locationsListModel.getName());
holder.review.setText(locationsListModel.getReview());
holder.locationPrice.setText(locationsListModel.getPrice());
}
#Override
public int getItemCount() {
return locationList.size();
}}
My Fragment:
public class LocationsListFragment extends Fragment {
private final LocationsListAdapter locationsListAdapter = new LocationsListAdapter();
private RecyclerView locationsList;
SimpleRatingBar ratingBar;
ArrayList<LocationsListModel> locationsListModels = new ArrayList<>();
public LocationsListFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static LocationsListFragment newInstance() {
LocationsListFragment fragment = new LocationsListFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_locations_list, container, false);
ratingBar = view.findViewById(R.id.ratingBar);
locationsList = view.findViewById(R.id.locations_lis);
setRecyclerViewItems();
return view;
}
private void setRecyclerViewItems() {
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(locationsList);
locationsList.setLayoutManager(new LinearLayoutManager(getContext(),
LinearLayoutManager.HORIZONTAL, true));
locationsList.setAdapter(locationsListAdapter);
locationsListModels.add(new LocationsListModel("Hotel 1","120 reviews","200$", "pic1"));
locationsListModels.add(new LocationsListModel("Hotel 2","102 reviews","120$", "pic2"));
locationsListModels.add(new LocationsListModel("Hotel 3","84 reviews","240$", "pic3"));
locationsListModels.add(new LocationsListModel("Hotel 4","113 reviews","220$", "pic4"));
locationsListModels.add(new LocationsListModel("Hotel 5","52 reviews","140$", "pic5"));
locationsListModels.add(new LocationsListModel("Hotel 6","57 reviews","190$", "pic6"));
locationsListModels.add(new LocationsListModel("Hotel 7","230 reviews","300$", "pic7"));
locationsListModels.add(new LocationsListModel("Hotel 8","131 reviews","90$", "pic8"));
locationsListModels.add(new LocationsListModel("Hotel 9","32 reviews","110$", "pic9"));
locationsListAdapter.setItems(locationsListModels);
locationsList.setHasFixedSize(true);
}}
You should use image in integer type -> R.drawable.p2
and your app/build.gradle add this :
compile 'com.github.bumptech.glide:glide:4.3.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
Your Model:
public class LocationsListModel {
public String name, review, price;
public int imageResource;
public LocationsListModel(String name, String review, String price, int imageResource) {
this.name = name;
this.review = review;
this.price = price;
this.imageResource = imageResource;
}
}
Your Adapter:
#Override
public void onBindViewHolder(LocationsListAdapter.LocationsListView holder, int position) {
LocationsListModel locationsListModel = locationList.get(position);
GlideApp.with(context).load(locationsListModel.imageResource)
.into(holder.imageView);
holder.locationName.setText(locationsListModel.name);
holder.review.setText(locationsListModel.review);
holder.locationPrice.setText(locationsListModel.price);
}
}
Your Fragment
locationsListModels.add(new LocationsListModel("Hotel 1","120 reviews","200$", R.drawable.pic1));
In Gradle:
compile 'com.github.bumptech.glide:glide:3.5.2'
Adapter:
Glide.with(context).load(imageurl).transform(new RoundImageTransform(context)).skipMemoryCache(true).into(ImageView);
Note : Remove RoundImageTransform -- It's for making an imageview as round in shape
Related
Base on guideline at https://github.com/firebase/FirebaseUI-Android/tree/master/firestore, I make a list items with FirestoreRecyclerAdapter but I don't know why the couldn't retrieve any data. In fact, the number view items are shown correctly, but the content always null. Anyone can help me. Below is source code:
Activity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseFirestore mDatabase;
private ViewPager mViewPager;
private CollectionReference mOrderRef;
private OrderAdapter mOrderAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_order_list);
mDatabase = FirebaseFirestore.getInstance();
mOrderRef = mDatabase.collection("order");
Query query = mOrderRef.limit(1000);
FirestoreRecyclerOptions<OrderInfo> options = new FirestoreRecyclerOptions.Builder<OrderInfo>().setQuery(query, OrderInfo.class).build();
mOrderAdapter = new OrderAdapter(options);
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view_order_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mOrderAdapter);
}
#Override
protected void onStart() {
super.onStart();
mOrderAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mOrderAdapter.stopListening();
}
Adapter:
public class OrderAdapter extends FirestoreRecyclerAdapter<OrderInfo, OrderAdapter.OrderHolder> {
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {#link
* FirestoreRecyclerOptions} for configuration options.
*
* #param options
*/
public OrderAdapter(#NonNull FirestoreRecyclerOptions<OrderInfo> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull OrderHolder holder, int position, #NonNull OrderInfo model) {
holder.txtTitle.setText(String.valueOf(model.getTitle()));
holder.txtCusName.setText(String.valueOf(model.getCusName()));
holder.txtDate.setText(String.valueOf(model.getDate()));
}
#NonNull
#Override
public OrderHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_item, parent, false);
return new OrderHolder(view);
}
class OrderHolder extends RecyclerView.ViewHolder{
TextView txtCusName;
TextView txtTitle;
TextView txtDate;
public OrderHolder(#NonNull View itemView) {
super(itemView);
txtCusName = itemView.findViewById(R.id.txt_customer_name);
txtTitle = itemView.findViewById(R.id.txt_title);
txtDate = itemView.findViewById(R.id.txt_date);
}
}
}
Data model:
public class OrderInfo {
private String mTitle;
private String mCusName;
private String mDate;
public OrderInfo(){
//default constructor
}
public OrderInfo(String title, String name, String date) {
this.mTitle = title;
this.mCusName = name;
this.mDate = date;
}
public String getTitle() {
return mTitle;
}
public String getCusName() {
return mCusName;
}
public void setCusName(String cusName) {
this.mCusName = cusName;
}
public String getDate() {
return mDate;
}
}
my database structure:
You data model is not aligned with database structure. Try to update it like below:
public class OrderInfo {
private String title;
private String name;
private String date;
public OrderInfo(){
//default constructor
}
public OrderInfo(String title, String name, String date) {
this.title = title;
this.name = name;
this.date = date;
}
public String getTitle() {
return title;
}
public String getName() {
return name;
}
public String getDate() {
return date;
}
}
Besides this don't forget to sync your project with firebase firestore.
I have the same code for another database and it works just fine, I have no Idea why it's not working here,
the onCreateViewHolder does not even get called.
(Appearently Stacks Overflow wants me to add more details to compensate for too much code so here's some unuseful Text , Text, Text , TEXT).
public class Course extends AppCompatActivity {
private RecyclerView mLocationView;
private DatabaseReference mLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course);
mLocation = FirebaseDatabase.getInstance().getReference("FINISHEDCOURSES");
mLocation.keepSynced(true);
mLocationView = (RecyclerView) findViewById(R.id.my_recycler_view);
mLocationView.setHasFixedSize(true);
mLocationView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Courses> options = new FirebaseRecyclerOptions.Builder<Courses>().setQuery(mLocation, Courses.class).build();
FirebaseRecyclerAdapter<Courses, CourseViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Courses, CourseViewHolder>
(options) {
#Override
protected void onBindViewHolder(#NonNull CourseViewHolder holder, int position, #NonNull Courses model) {
holder.setText(model.getDate(), model.getDistance(), model.getDriver(), model.getPrice());
}
#NonNull
#Override
public CourseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.courses_rows, parent, false);
return new CourseViewHolder(view);
}
};
mLocationView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public static class CourseViewHolder extends RecyclerView.ViewHolder{
View mView;
public CourseViewHolder(View itemView){
super(itemView);
mView = itemView;
}
public void setText(String Date, String start, String end, String price){
TextView dateText = mView.findViewById(R.id.dateText);
TextView startText = mView.findViewById(R.id.depart_text);
TextView endText = mView.findViewById(R.id.end_text);
TextView priceText = mView.findViewById(R.id.price);
dateText.setText(Date);
startText.setText(start);
endText.setText(end);
priceText.setText(price);
}
}
The Courses Class
public class Courses {
private String driver, date, distance, preWaitTime, price, waitTime, client;
public Courses() {
}
public Courses(String driver, String date, String distance, String preWaitTime, String price, String waitTime, String client) {
this.driver = driver;
this.date = date;
this.distance = distance;
this.preWaitTime = preWaitTime;
this.price = price;
this.waitTime = waitTime;
this.client = client;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getPreWaitTime() {
return preWaitTime;
}
public void setPreWaitTime(String preWaitTime) {
this.preWaitTime = preWaitTime;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getWaitTime() {
return waitTime;
}
public void setWaitTime(String waitTime) {
this.waitTime = waitTime;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
}
Here's The Database Structure :
Sorry I should have commented but i do not have enough reputation to do so.
I cannot see anything similar to this in your code.
FirebaseRecyclerAdapter<Courses, CourseViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Courses, CourseViewHolder>(
Courses.class,
R.layout.Courses,// should be your layout name
CourseViewHolder.class,
mLocation
) {
#Override
protected void populateViewHolder(CourseViewHolder viewHolder, category model, final int position) {
viewHolder.setName(model.getName());
viewHolder.setImage(getApplicationContext(),model.getImage());
I am trying to load data from an api online but am having an issue with the views loading. When I try to run the emulator, a blank screen shows up. Any idea why? I am guessing my issue is somewhere within how I am loading the gridview but I have not been able to figure it out.
MainActivity
public class MainActivity extends AppCompatActivity {
String SEARCH_TERM = "popular";
private RecyclerView mRecyclerView;
private MovieAdapter mMovieAdapter;
private GridLayoutManager gridLayoutManager;
private List<Movie> movieData;
/*
API KEY
https://api.themoviedb.org/3/movie/550?api_key=1f5029b7d824dee72f4d4a156dac90ed
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
gridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
mMovieAdapter = new MovieAdapter(this, movieData);
mRecyclerView.setAdapter(mMovieAdapter);
movieData = new ArrayList<>();
loadMovieData();
}
private void loadMovieData() {
new FetchMovieTask().execute(SEARCH_TERM);
}
public class FetchMovieTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
final String MOVIES_RESULTS = "results";
final String MOVIES_POSTER_IMAGE = "poster_path";
final String MOVIES_TITLE = "title";
final String RELEASE_DATE = "release_date";
URL moviesUrl = NetworkUtils.buildUrl(SEARCH_TERM);
try {
String jsonMoviesResponse = NetworkUtils.getReponseFromHttpUrl(moviesUrl);
JSONObject moviesJson = new JSONObject(jsonMoviesResponse);
JSONArray moviesArray = moviesJson.getJSONArray(MOVIES_RESULTS);
for (int i = 0; i < moviesArray.length(); i++) {
String moviePoster;
String movieTitle;
String movieReleaseDate;
JSONObject movie = moviesArray.getJSONObject(i);
moviePoster = ("http://image.tmdb.org/t/p/w185/" + movie.getString(MOVIES_POSTER_IMAGE));
movieTitle = movie.getString(MOVIES_TITLE);
movieReleaseDate = movie.getString(RELEASE_DATE);
Log.i("MoviteTitle", movieTitle);
Log.i("ReleaseDate", movieReleaseDate);
Log.i("Image", moviePoster);
Movie data = new Movie(movieTitle, movieReleaseDate, moviePoster);
movieData.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
mMovieAdapter.notifyDataSetChanged();
}
}
}
Adapter Class
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieAdapterViewHolder>{
private List<Movie> mMovieData;
private Context context;
public MovieAdapter(Context context, List<Movie> movieData) {
this.context = context;
this.mMovieData = movieData;
}
#Override
public void onBindViewHolder(#NonNull MovieAdapterViewHolder holder, int position) {
holder.mTitleTextView.setText(mMovieData.get(position).getTitle());
holder.mReleaseDateTextView.setText(mMovieData.get(position).getDate());
Picasso.with(context).load(mMovieData.get(position).getMoviePoster()).into(holder.mImageView);
}
#NonNull
#Override
public MovieAdapterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.cardview_item, parent, false);
return new MovieAdapterViewHolder(view);
}
#Override
public int getItemCount() {
if (null == mMovieData)
return 0;
return mMovieData.size();
}
public class MovieAdapterViewHolder extends RecyclerView.ViewHolder {
public final TextView mTitleTextView;
public final TextView mReleaseDateTextView;
public final ImageView mImageView;
public MovieAdapterViewHolder(View itemView) {
super(itemView);
mTitleTextView = itemView.findViewById(R.id.title_text_view);
mReleaseDateTextView = itemView.findViewById(R.id.release_date_text_view);
mImageView = itemView.findViewById(R.id.image_data);
}
}
}
Movie Class
public class Movie {
private String Title;
private String Date;
private String MoviePoster;
public Movie(String title, String date, String moviePoster) {
Title = title;
Date = date;
MoviePoster = moviePoster;
}
public Movie() {
}
public String getTitle() {
return Title;
}
public String getDate() {
return Date;
}
public String getMoviePoster() {
return MoviePoster;
}
public void setTitle(String title) {
Title = title;
}
public void setDate(String date) {
Date = date;
}
public void setMoviePoster(String moviePoster) {
MoviePoster = moviePoster;
}
}
Info : Java is all pass by value.
Issue : you are passing empty list reference to adapter and later initialising the list but in adapter it is still null so adapter will never receive the added value in list so do
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
gridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
movieData = new ArrayList<>();
//^^^^^^^^^^^^^^^^^^^^^^^^^ do it before
mMovieAdapter = new MovieAdapter(this, movieData);
mRecyclerView.setAdapter(mMovieAdapter);
loadMovieData();
i am a newbie and i am trying to add some data in to the recyclerview from firbase db.but it showing the not serializable error. i searched everywhere and found couple of answers to make classes static and variables public but still not working, here are my codes
My Adapter
public class CardViewAdapter extends FirebaseRecyclerAdapter<MainpageCardModel,CardViewAdapter.Recyclerviewholder>{
public Context mcontext;
public List<MainpageCardModel> cakeslist;
public CardViewAdapter(DatabaseReference ref){
super(MainpageCardModel.class,R.layout.card,CardViewAdapter.Recyclerviewholder.cl ass,ref);
}
#Override
protected void populateViewHolder(Recyclerviewholder viewHolder, MainpageCardModel model, int position) {
viewHolder.ItemName.setText(MainpageCardModel.getItemName());
viewHolder.ItemPrice.setText(MainpageCardModel.getItemPrice());
if(MainpageCardModel.getItemImage() == null){
viewHolder.CardviewImageView.setImageDrawable(ContextCompat.getDrawable(mcontext,
R.drawable.ic_cake_dark));
}
else {
Glide.with(mcontext)
.load(MainpageCardModel.getItemImage())
.into(viewHolder.CardviewImageView);
}
}
public static class Recyclerviewholder extends RecyclerView.ViewHolder {
public ImageView CardviewImageView;
public TextView ItemName, ItemPrice;
public Recyclerviewholder(View itemView) {
super(itemView);
CardviewImageView = (ImageView) itemView.findViewById(R.id.cakepic_cardview);
ItemName = (TextView) itemView.findViewById(R.id.caketitle_cardview);
ItemPrice = (TextView) itemView.findViewById(R.id.cakeprice_cardview);
}
}
My model class
public Class MainpageCardModel{
public static String itemName;
public static String itemImage;
public static String itemPrice;
public MainpageCardModel(){
}
public MainpageCardModel(String itemName, String itemImage, String itemPrice){
this.itemImage=itemImage;
this.itemName=itemName;
this.itemPrice=itemPrice;
}
public static String getItemName() {
return itemName;
}
public void setItemName(String itemName){
this.itemName = itemName;
}
public static String getItemImage(){
return itemImage;
}
public void setItemImage(String itemImage){
this.itemImage= itemImage;
}
public static String getItemPrice(){
return itemPrice;
}
public void setItemPrice(String itemPrice) {
this.itemPrice = itemPrice;
}
}
My Fragment
private static final String TAG = "FreshCreamFragment";
public static final String MENU_CHILD = "FreshCream";
private String Cakename, cakeprice, cakeurl;
private RecyclerView mRecyclerView;
private DatabaseReference mFirebaseDatabaseReference;
private CardViewAdapter adapterl;
private GridLayoutManager gridLayoutManager;
public List<MainpageCardModel> cakeslist;
ProgressBar mprogressbar;
MainpageCardModel mainpageCardModel;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cakeslist= new ArrayList<>();
adapterl = new CardViewAdapter(mFirebaseDatabaseReference.child(MENU_CHILD));
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("menu");
mFirebaseDatabaseReference.child(MENU_CHILD).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String,String> cakedetails = (Map)dataSnapshot.getValue();
Cakename= cakedetails.get("Item_name");
cakeprice = cakedetails.get("Item_price");
cakeurl = cakedetails.get("url");
mainpageCardModel = new MainpageCardModel(Cakename,cakeurl,cakeprice);
cakeslist.add(mainpageCardModel);
adapterl.notifyDataSetChanged();
mprogressbar.setVisibility(ProgressBar.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fresh_cream_fragment, container, false);
mprogressbar = (ProgressBar) rootview.findViewById(R.id.progressBar3);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.freshcream_recyclerview);
gridLayoutManager = new GridLayoutManager(getContext(),2);
mRecyclerView.setLayoutManager(gridLayoutManager);
mRecyclerView.setAdapter(adapterl);
return rootview;
}
}
MYdb
mydbscreenshot
looks like you have following lines in wrong order?
adapterl = new CardViewAdapter(mFirebaseDatabaseReference.child(MENU_CHILD));
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("menu");
i create application call api the moves DB with retrofit library and recyclerViewe
when user choose the movie Show activity for detail movies
Now i implement recyclerView with ritrofit to create fetch the popular movie data,
this MoviesApiService class :
public interface MoviesApiService {
#GET("/movie/popular")
void getPopularMovies(Callback<Movie.MovieResult> cb); }
this model class :
package com.walkatheri.popularmovies;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
*/
public class Movie implements Parcelable{
private String title;
#SerializedName("poster_path")
private String poster;
#SerializedName("overview")
private String description;
#SerializedName("backdrop_path")
private String backdrop;
public Movie() {}
protected Movie(Parcel in) {
title = in.readString();
poster = in.readString();
description = in.readString();
backdrop = in.readString();
}
public static final Creator<Movie> CREATOR = new Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPoster() {
return "http://image.tmdb.org/t/p/w500" + poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getBackdrop() {
return "http://image.tmdb.org/t/p/w500" + backdrop;
}
public void setBackdrop(String backdrop) {
this.backdrop = backdrop;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
parcel.writeString(poster);
parcel.writeString(description);
parcel.writeString(backdrop);
}
public static class MovieResult {
private List<Movie> results;
public List<Movie> getResults() {
return results;
}
}
}
class detail movie :
public class MovieDetailActivity extends AppCompatActivity {
public static final String EXTRA = "movie";
private Movie mMovie;
ImageView backdrop;
ImageView poster;
TextView title;
TextView description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
if (getIntent().hasExtra(EXTRA)) {
mMovie = getIntent().getParcelableExtra(EXTRA);
} else {
throw new IllegalArgumentException("Detail activity must receive a movie parcelable");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
CollapsingToolbarLayout toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
toolbarLayout.setTitle(mMovie.getTitle());
backdrop = (ImageView) findViewById(R.id.backdrop);
title = (TextView) findViewById(R.id.movie_title);
description = (TextView) findViewById(R.id.movie_description);
poster = (ImageView) findViewById(R.id.movie_poster);
title.setText(mMovie.getTitle());
description.setText(mMovie.getDescription());
Picasso.with(this)
.load(mMovie.getPoster())
.into(poster);
Picasso.with(this)
.load(mMovie.getBackdrop())
.into(backdrop);
}
}
this mainActivity class :
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
mAdapter = new MoviesAdapter(this);
mRecyclerView.setAdapter(mAdapter);
getPopularMovies();
}
private void getPopularMovies() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://api.themoviedb.org/3")
.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addEncodedQueryParam("api_key", "Key_API");
}
})
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
MoviesApiService service = restAdapter.create(MoviesApiService.class);
service.getPopularMovies(new Callback<Movie.MovieResult>() {
#Override
public void success(Movie.MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class MovieViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public MovieViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public static class MoviesAdapter extends RecyclerView.Adapter<MovieViewHolder> {
private List<Movie> mMovieList;
private LayoutInflater mInflater;
private Context mContext;
public MoviesAdapter(Context context) {
this.mContext = context;
this.mInflater = LayoutInflater.from(context);
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
View view = mInflater.inflate(R.layout.row_movie, parent, false);
final MovieViewHolder viewHolder = new MovieViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = viewHolder.getAdapterPosition();
Intent intent = new Intent(mContext, MovieDetailActivity.class);
intent.putExtra(MovieDetailActivity.EXTRA, mMovieList.get(position));
mContext.startActivity(intent);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Movie movie = mMovieList.get(position);
Picasso.with(mContext)
.load(movie.getPoster())
.placeholder(R.color.colorAccent)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return (mMovieList == null) ? 0 : mMovieList.size();
}
public void setMovieList(List<Movie> movieList) {
this.mMovieList = new ArrayList<>();
this.mMovieList.addAll(movieList);
notifyDataSetChanged();
}
}
}
now how can be able to fetch both popular movie data and high-rated movie data from https://developers.themoviedb.org ? can you help me ?
You have a method in your MainActivity called getPopularMovies() where you call service.getPopularMovies(), which uses the MoviesApiService #GET("/movie/popular"). You could create a similar API for high-rated movies, something like:
#GET("/movie/high_rated")
void getHighRatedMovies(Callback<Movie.MovieResult> cb);
Then create a similar getHighRatedMovies() method and depending on what the user selects, make a call to that method. The only difference would be you would call service.getHighRatedMovies instead of service.getPopularMovies().
To simplify the code to just one method, you could make a method called getMovies(), and then at the point when you initialize service.(something), set the correct method call.