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.
Related
and thank you for your attention to my request.
I'm a newbie on Andorid Studio and I'm developing an App, it has to show a list of Events, Courses and News. There is a DrawerLayout which allow navigating into Event's, course's and news's area, each area has each specific RecyclerView, but into the home activity, I have to show all the items (Event, Course and News).
I create an Adapter for each item (because they have different properties) and each section (fragment) works properly but now I'm stuck with the main activity (the home).
Here are the models for explaining the difference between them:
Event
public class Event {
private int id;
private String title;
private String description;
private LocalDateTime startingDate;
private LocalDateTime endingDate;
private String cost;
private String website;
private Category category;
private Venue venue;
private Organizer organizer;
private String status;
private int resImage;
public Event(int id, String title, String description, LocalDateTime startingDate, LocalDateTime endingDate, String cost, String website, Category category, Venue venue, Organizer organizer, int image) {
this.id = id;
this.title = title;
this.description = description;
this.startingDate = startingDate;
this.endingDate = endingDate;
this.cost = cost;
this.website = website;
this.category = category;
this.venue = venue;
this.organizer = organizer;
this.resImage = image;
}
public Event(){}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDateTime getStartingDate() {
return startingDate;
}
public void setStartingDate(LocalDateTime startingDate) {
this.startingDate = startingDate;
}
public LocalDateTime getEndingDate() {
return endingDate;
}
public void setEndingDate(LocalDateTime endingDate) {
this.endingDate = endingDate;
}
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public Category getCategory() {
return category;
}
public Venue getVenue() {
return venue;
}
public Organizer getOrganizer() {
return organizer;
}
public String getStatus() {
return status;
}
public int getResImage() {
return resImage;
}
}
News:
public class News {
private int id;
private String title;
private String content;
private int resImage;
public News(int id, String title, String content, int image) {
this.id = id;
this.title = title;
this.content = content;
this.resImage = image;
}
public News(){}
public int getId(){
return this.id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setDescription(String description) {
this.content = content;
}
public int getResImage() {
return resImage;
}
public void setResImage(int resImage) {
this.resImage = resImage;
}
}
Courses
public Course(int id, String title, String content, float price, LocalDate startingDate, int availablePlace, Teacher teacher, CourseCategory courseCategory, Location location, Duration duration, Level level, int resImage) {
this.id = id;
this.title = title;
this.content = content;
this.price = price;
this.startingDate = startingDate;
this.availablePlace = availablePlace;
this.teacher = teacher;
this.courseCategory = courseCategory;
this.location = location;
this.duration = duration;
this.level = level;
this.resImage = resImage;
}
public int getId() {
return 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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public LocalDate getStartingDate() {
return startingDate;
}
public void setStartingDate(LocalDate startingDate) {
this.startingDate = startingDate;
}
public int getAvailablePlace() {
return availablePlace;
}
public void setAvailablePlace(int availablePlace) {
this.availablePlace = availablePlace;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public CourseCategory getCourseCategory() {
return courseCategory;
}
public void setCourseCategory(CourseCategory courseCategory) {
this.courseCategory = courseCategory;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Level getLevel() {
return level;
}
public int getResImage() {
return resImage;
}
public void setResImage(int resImage) {
this.resImage = resImage;
}
}
Here is the Adapters:
EventAdapter
public class EventViewAdapter extends RecyclerView.Adapter<EventViewAdapter.EventViewHolder> {
ArrayList<Event> eventList;
Context context;
public EventViewAdapter(ArrayList<Event> eventList, Context context) {
this.eventList = eventList;
this.context = context;
}
public EventViewAdapter() {
}
public static class EventViewHolder extends RecyclerView.ViewHolder {
ImageView eventImage;
TextView startingDate, place, title;
LinearLayout cellLayout;
EventViewHolder(View eventView) {
super(eventView);
eventImage = eventView.findViewById(R.id.event_image);
startingDate = eventView.findViewById(R.id.event_starting_date);
place = eventView.findViewById(R.id.event_place);
title = eventView.findViewById(R.id.event_title);
cellLayout = eventView.findViewById(R.id.event_cell_layout);
}
}
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_cell_def, parent, false);
EventViewHolder evh = new EventViewHolder(view);
return evh;
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, int position) {
final String title = eventList.get(position).getTitle();
final String description = eventList.get(position).getDescription();
final String place = eventList.get(position).getVenue().getCity();
final String address = eventList.get(position).getVenue().getAddress();
final String startDate = String.valueOf(eventList.get(position).getStartingDate().toLocalDate());
final String startTime = String.valueOf(eventList.get(position).getStartingDate().getHour() + ":" + String.valueOf(eventList.get(position).getStartingDate().getMinute()));
final String endDate = String.valueOf(eventList.get(position).getEndingDate().toLocalDate());
final String cost = eventList.get(position).getCost();
final String website = eventList.get(position).getWebsite();
final String category = eventList.get(position).getCategory().getName();
final String organizer = eventList.get(position).getOrganizer().getOrganizer();
final String organizerWebsite = eventList.get(position).getOrganizer().getWebsite();
final int image = eventList.get(position).getResImage();
holder.eventImage.setImageResource(image);
holder.startingDate.setText(startDate);
holder.place.setText(place);
holder.title.setText(title);
holder.cellLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailEventActivity.class);
intent.putExtra("title", title);
intent.putExtra("description", description);
intent.putExtra("place", place);
intent.putExtra("address", address);
intent.putExtra("startDate", startDate);
intent.putExtra("startTime", startTime);
intent.putExtra("endDate", endDate);
intent.putExtra("cost", cost);
intent.putExtra("website", website);
intent.putExtra("category", category);
intent.putExtra("organizer", organizer);
intent.putExtra("orgWebsite", organizerWebsite);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Hai premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return eventList.size();
}
public void eventSetSearchOperation(ArrayList<Event> newList){
eventList = new ArrayList<>();
eventList.addAll(newList);
notifyDataSetChanged();
}
}
CourseAdapter:
public class CourseViewAdapter extends RecyclerView.Adapter<CourseViewAdapter.CourseViewHolder> {
ArrayList<Course> courseList;
Context context;
public CourseViewAdapter(ArrayList<Course> courseList, Context context) {
this.courseList = courseList;
this.context = context;
}
public CourseViewAdapter(){}
public static class CourseViewHolder extends RecyclerView.ViewHolder {
ImageView courseImage;
TextView startingDate, place, title;
LinearLayout courseLinear;
CourseViewHolder(View courseView){
super(courseView);
courseImage = courseView.findViewById(R.id.course_image);
startingDate = courseView.findViewById(R.id.course_starting_date);
place = courseView.findViewById(R.id.course_place);
title = courseView.findViewById(R.id.course_title);
courseLinear = courseView.findViewById(R.id.course_cell_layout);
}
}
#NonNull
#Override
public CourseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell_def, parent, false);
CourseViewHolder cvh = new CourseViewHolder(view);
return cvh;
}
#Override
public void onBindViewHolder(#NonNull CourseViewHolder holder, int position) {
final String title = courseList.get(position).getTitle();
final String category = courseList.get(position).getCourseCategory().getName();
final String description = courseList.get(position).getContent();
final String place = courseList.get(position).getLocation().getName();
final String startDate = String.valueOf(courseList.get(position).getStartingDate());
final int availablePlace = courseList.get(position).getAvailablePlace();
final String teacher = courseList.get(position).getTeacher().getName();
final String teacherEmail = courseList.get(position).getTeacher().getEmail();
final String teacherMobile = courseList.get(position).getTeacher().getPhone();
final String duration = courseList.get(position).getDuration().getName();
final String level = courseList.get(position).getLevel().getName();
final String price = String.valueOf(courseList.get(position).getPrice());
final int image = courseList.get(position).getResImage();
holder.courseImage.setImageResource(image);
holder.startingDate.setText(startDate);
holder.place.setText(place);
holder.title.setText(title);
holder.courseLinear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailCourseActivity.class);
intent.putExtra("title", title);
intent.putExtra("category", category);
intent.putExtra("content", description);
intent.putExtra("startDate", startDate);
intent.putExtra("availablePlace", availablePlace);
intent.putExtra("teacher", teacher);
intent.putExtra("teacherEmail", teacherEmail);
intent.putExtra("teacherMobile", teacherMobile);
intent.putExtra("duration", duration);
intent.putExtra("price", price);
intent.putExtra("place", place);
intent.putExtra("level", level);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Hai premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return courseList.size();
}
public void courseSetSearchOperation(ArrayList<Course> newList){
courseList = new ArrayList<>();
courseList.addAll(newList);
notifyDataSetChanged();
}
}
News:
public class NewsViewAdapter extends RecyclerView.Adapter<NewsViewAdapter.NewsViewHolder> {
ArrayList<News> newsList;
Context context;
public NewsViewAdapter(ArrayList<News> newsList, Context context) {
this.newsList = newsList;
this.context = context;
}
public NewsViewAdapter(){}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView newsImage;
TextView newsTitle, newsContent;
LinearLayout newsLayout;
NewsViewHolder(View newView){
super(newView);
newsImage = newView.findViewById(R.id.news_image);
newsTitle = newView.findViewById(R.id.news_title);
newsContent = newView.findViewById(R.id.news_content);
newsLayout = newView.findViewById(R.id.news_cell_layout);
}
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_cell_def, parent, false);
NewsViewHolder nvh = new NewsViewHolder(view);
return nvh;
}
#Override
public void onBindViewHolder(#NonNull NewsViewHolder holder, int position) {
final String title = newsList.get(position).getTitle();
final String content = newsList.get(position).getContent();
final int image = newsList.get(position).getResImage();
holder.newsImage.setImageResource(image);
holder.newsTitle.setText(title);
holder.newsContent.setText(content);
holder.newsLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailNewsActivity.class);
intent.putExtra("title", title);
intent.putExtra("content", content);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return newsList.size();
}
public void newsSetSearchOperation(ArrayList<News> newList){
newsList = new ArrayList<>();
newsList.addAll(newList);
notifyDataSetChanged();
}
}
Each specific list of item is into a fragment, indeed here is the Main Activity (home), where I would like to display a RecyclerView of all the itmes:
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView mNavigationView;
private Toolbar toolbar;
private ActionBarDrawerToggle drawerToggle;
private FloatingActionButton fab;
private RecyclerView mRecyclerView;
private ImageView openFilter;
private SearchView searchView;
private DataMock dataMock = new DataMock();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view_main);
drawerLayout = findViewById(R.id.drawer_layout);
mNavigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
openFilter = findViewById(R.id.filter_icon);
searchView = findViewById(R.id.action_search);
fab = findViewById(R.id.fab);
fab.show();
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
searchView.setQueryHint(getString(R.string.search_hint));
drawerToggle = setupDrawerToggle();
drawerToggle.setDrawerIndicatorEnabled(true);
drawerToggle.syncState();
drawerLayout.setDrawerListener(drawerToggle);
drawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
});
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment nextFragment;
switch (menuItem.getItemId()){
case R.id.event_list:
nextFragment = new EventFragment();
break;
case R.id.course_list:
nextFragment = new CourseFragment();
break;
case R.id.news_list:
nextFragment = new NewsFragment();
break;
default:
throw new IllegalArgumentException("No Fragment for the given menu item");
}
if (nextFragment != null){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.anchor_point, nextFragment)
.commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
drawerLayout.closeDrawer(mNavigationView);
}
return false;
}
});
openFilter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialog filterDialog = new BottomSheetDialog();
filterDialog.show(getSupportFragmentManager(), "filter dialog opened!");
}
});
// mRecyclerView.setHasFixedSize(true);
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// mRecyclerView.setLayoutManager(layoutManager);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private ActionBarDrawerToggle setupDrawerToggle() {
// NOTE: Make sure you pass in a valid toolbar reference. ActionBarDrawToggle() does not require it
// and will not render the hamburger icon without it.
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
public void backToHome(View view){
for (Fragment fragment : getSupportFragmentManager().getFragments()){
if (fragment != null && (fragment instanceof CourseFragment || fragment instanceof EventFragment || fragment instanceof NewsFragment)){
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
toolbar.setTitle("WePress");
fab.show();
}
}
Toast.makeText(this, "Premuto sul logo", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawer(mNavigationView);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
public void addItem(View view){
PopupMenu popupMenu = new PopupMenu(MainActivity.this, fab);
popupMenu.getMenuInflater().inflate(R.menu.fab_main_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.add_event:
Toast.makeText(MainActivity.this, "Pronti per aggiungere un evento", Toast.LENGTH_SHORT).show();
Intent intentEvent = new Intent(MainActivity.this, AddItemActivity.class);
intentEvent.putExtra("isFrom", "event");
startActivity(intentEvent);
break;
case R.id.add_course:
Toast.makeText(MainActivity.this, "Pronti per aggiungere un corso", Toast.LENGTH_SHORT).show();
Intent intentCourse = new Intent(MainActivity.this, AddItemActivity.class);
intentCourse.putExtra("isFrom", "course");
startActivity(intentCourse);
break;
case R.id.add_news:
Toast.makeText(MainActivity.this, "Pronti per aggiungere una news", Toast.LENGTH_SHORT).show();
Intent intentNews = new Intent(MainActivity.this, AddItemActivity.class);
intentNews.putExtra("isFrom", "news");
startActivity(intentNews);
break;
}
return true;
}
});
popupMenu.show();
}
}
if it's possible to show the list with differents layouts, can you also suggest a way to improve the quality of my code avoiding to repeat lines of code? If I'm not wrong, I would like to re-use each Adapter or part of them that I can put into a specific class (?).
Thank you so much for your help!
If I'm missing some information, please ask me in order to edit the post.
You must do only one adapter (using view type) with a view model class
that contain either an event or a news or a course
the adapter should be something like that:
public class EventViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_EVENT = 10;
private static final int TYPE_COURSE = 11;
private static final int TYPE_NEWS = 12;
ArrayList<EventViewModel> eventList;
Context context;
public EventViewAdapter(ArrayList<EventViewModel> eventList, Context context) {
this.eventList = eventList;
this.context = context;
}
public EventViewAdapter() {
}
#Override
public int getItemViewType(int position) {
EventViewModel event = eventList.get(position);
if (event.isEvent()) {
return TYPE_EVENT ;
} else if(event.isCourse()) {
return TYPE_COURSE;
} else {
return TYPE_NEWS;
}
}
public static class EventViewHolder extends RecyclerView.ViewHolder {
ImageView eventImage;
//....
EventViewHolder(View eventView) {
super(eventView);
eventImage = eventView.findViewById(R.id.event_image);
//.....
}
}
public static class CourseViewHolder extends RecyclerView.ViewHolder {
ImageView courseImage;
//.....
CourseViewHolder(View courseView) {
super(courseView);
courseImage = courseView.findViewById(R.id.course_image);
//.....
}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView newsImage;
//.....
NewsViewHolder(View newView){
super(newView);
newsImage = newView.findViewById(R.id.news_image);
//.....
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == TYPE_EVENT) {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_cell_def, parent, false);
return new EventViewHolder (rootView);
} else if (viewType == TYPE_COURSE) {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell_def, parent, false);
return new CourseViewHolder(rootView);
} else {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_cell_def, parent, false);
return new NewsViewHolder(rootView);
}
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, int position)
{
final EventViewModel eventViewModel = eventList.get(position);
if (eventViewModel .isEvent()) {
onBindEvent(holder, eventViewModel.getEvent());
} else if(eventViewModel .isCourse()) {
onBindCourse(holder, eventViewModel.getCourse());
} else {
onBindNews(holder, eventViewModel.getNews());
}
}
private void onBindEvent(RecyclerView.ViewHolder holder, Event event) {
EventViewHolder eventHolder= (EventViewHolder ) holder;
final String title = event.getTitle();
final String description = event.getDescription();
// others ...
holder.eventImage.setImageResource(image);
holder.startingDate.setText(startDate);
// others ...
holder.cellLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// ...
}
#Override
public int getItemCount() {
return eventList.size();
}
public void eventSetSearchOperation(ArrayList<Event> newList){
eventList = new ArrayList<>();
eventList.addAll(newList);
notifyDataSetChanged();
}
}
And a View Model classes like that :
public class EventViewModel() {
private Event mEvent;
private Course mCourse;
private News mNews;
private EventViewModel(Event event, Course course, News news) {
this.mEvent = event;
this.mCourse = course;
this.mNews = news;
}
public boolean isEvent() {
return mEvent != null
}
public boolean isCourse() {
return mCourse != null
}
public boolean isNews() {
return mNews != null
}
public static EventViewModel getEventInstance(Event event) {
return new EventViewModel(event, null, null
}
public static EventViewModel getCourseInstance(Course course) {
return new EventViewModel(null, course, null
}
public static EventViewModel getNewsInstance(News news) {
return new EventViewModel(null, null, news
}
public Event getEvent() {
return mEvent;
}
public Event getCourse() {
return mScore;
}
public Event getNews() {
return mNews;
}
}
You can use this adapter in all of your fragments (event, course, news) and each fragment contaions a list of EventViewModel with only its specific type. The adapter display in the main activity contains EventViewModel of all types to display all events.
friends...
In my project, I am creating a list of images from the server and showing in Recyclerview.
now I want to remove a particular item from the list when I click on the verify button.
I tried to hide holder.itemview but its see again when I scroll.
I just want to remove or hide that item which is verified once.
here is my code :
1) Main activity
public class MainActivity extends AppCompatActivity {
private static final String url = "www.mysite.com/api/api-id-list.php?action=imgs";
private ProgressDialog mDetailProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main_activity);
LoadRecyclerView();
}
private void LoadRecyclerView() {
mDetailProgress = new ProgressDialog(this);
mDetailProgress.setTitle("Loading images");
mDetailProgress.setMessage("Please Wait...");
mDetailProgress.setCanceledOnTouchOutside(false);
mDetailProgress.show();
final RecyclerView imgList = (RecyclerView) findViewById(R.id.imgList);
imgList.setLayoutManager(new LinearLayoutManager(this));
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Image[] images = gson.fromJson(response, Image[].class);
imgList.setAdapter(new ImageAdapter(MainActivity.this, images));
mDetailProgress.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(), "Something went wrong..!", Toast.LENGTH_LONG);
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}}
2) ImageAdapter
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private ProgressDialog mDetailProgress;
private Context context;
private Image[] data;
Button btn_ban, btn_verify;
private View view;
public ImageAdapter (Context context, Image[] data) {
this.context = context;
this.data = data;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.single_item, parent, false);
return new ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ImageViewHolder holder, final int position) {
final Image imagelist = data[position];
holder.userCode.setText(imagelist.getCode());
Glide.with(holder.userImage.getContext()).load(imagelist.getIdPhoto()).into(holder.userImage);
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.itemView.setVisibility(View.GONE);
}
});
}
#Override
public int getItemCount() { return data.length; }
public class ImageViewHolder extends RecyclerView.ViewHolder {
TextView userCode;
ImageView userImage;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
userImage = (ImageView) itemView.findViewById(R.id.card_iv_img);
userCode = (TextView) itemView.findViewById(R.id.card_tv_code);
btn_ban = (Button) itemView.findViewById(R.id.btn_ban);
btn_verify = (Button) itemView.findViewById(R.id.btn_verify);
}
}}
3) Image.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Image {
#SerializedName("per_ID")
#Expose
private String perID;
#SerializedName("code")
#Expose
private String code;
#SerializedName("first_nm")
#Expose
private String firstNm;
#SerializedName("last_nm")
#Expose
private String lastNm;
#SerializedName("photo_ID")
#Expose
private String photoID;
#SerializedName("id_photo")
#Expose
private String idPhoto;
public String getPerID() {
return perID;
}
public void setPerID(String perID) {
this.perID = perID;
}
public Image withPerID(String perID) {
this.perID = perID;
return this;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Image withCode(String code) {
this.code = code;
return this;
}
public String getFirstNm() {
return firstNm;
}
public void setFirstNm(String firstNm) {
this.firstNm = firstNm;
}
public Image withFirstNm(String firstNm) {
this.firstNm = firstNm;
return this;
}
public String getLastNm() {
return lastNm;
}
public void setLastNm(String lastNm) {
this.lastNm = lastNm;
}
public Image withLastNm(String lastNm) {
this.lastNm = lastNm;
return this;
}
public String getPhotoID() {
return photoID;
}
public void setPhotoID(String photoID) {
this.photoID = photoID;
}
public Image withPhotoID(String photoID) {
this.photoID = photoID;
return this;
}
public String getIdPhoto() {
return idPhoto;
}
public void setIdPhoto(String idPhoto) {
this.idPhoto = idPhoto;
}
public Image withIdPhoto(String idPhoto) {
this.idPhoto = idPhoto;
return this;
}}
First make data not array, but List, so it's easy to remove item;
Secondly set listener for verify button inside ViewHolder and inside OnClick remove item and notify adapter.
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
data.remove(position);
notifyItemRemoved(position);
}
});
Note: Setting OnClickListener inside ViewHolder makes sure that only correct item is removed by using getAdapterPosition() to get correct position.
Position provided by onBindViewHolder might be invalid after new items are inserted.
im using thoughtbot expandable recyclerview (https://github.com/thoughtbot/expandable-recycler-view) and i can't get to expand groups on clicks. also i know that the child items are not even binded (not sure if they were supposed to bind or only on expanding of group.)
my view holders:
public class PlaylistViewHolder extends GroupViewHolder {
private TextView mPlaylistName, mPlaylistCount;
private ImageView arrow;
ExpandableListView.OnGroupClickListener listener;
public PlaylistViewHolder(View itemView) {
super(itemView);
mPlaylistName = itemView.findViewById(R.id.playlistNameView);
mPlaylistCount = itemView.findViewById(R.id.videosCount);
arrow = itemView.findViewById(R.id.expandBtn);
}
public void setCurrentPlaylist(YoutubePlaylist playlist){
Log.e("###",playlist.toString());
mPlaylistName.setText(playlist.getListTitle());
mPlaylistCount.setText("5");
}
}
/////
public class VideoViewHolder extends ChildViewHolder {
TextView mVideoName,mVideoLinkView;
ImageView mVideoThumb;
public VideoViewHolder(View itemView) {
super(itemView);
mVideoName = itemView.findViewById(R.id.videoNameView);
mVideoThumb = itemView.findViewById(R.id.videoThumb);
mVideoLinkView = itemView.findViewById(R.id.videoLinkView);
}
public void onBind(YoutubeVideo video){
Log.e("###","Video binded!!!!!!!");
mVideoName.setText(video.getTitle());
mVideoLinkView.setText(video.getThumbnailLink());
}
}
my classes:
the group class:
public class YoutubePlaylist extends ExpandableGroup<YoutubeVideo> {
#SerializedName("ListTitle")
private String title;
#SerializedName("ListItems")
private ArrayList<YoutubeVideo> videos;
public YoutubePlaylist(String title, List<YoutubeVideo> items) {
super(title, items);
this.title = title;
}
public String getListTitle() {
return title;
}
public void setListTitle(String listTitle) {
this.title = listTitle;
}
public ArrayList<YoutubeVideo> getVideos() {
return videos;
}
public void setVideos(ArrayList<YoutubeVideo> videos) {
this.videos = videos;
}
#Override
public String toString() {
return "YoutubePlaylist{" +
"title='" + title + '\'' +
", videos=" + videos +
'}';
}
}
my child class:
class YoutubeVideo implements Parcelable {
#SerializedName("Title")
private String title;
#SerializedName("link")
private String linkToVideo;
#SerializedName("thumb")
private String thumbnailLink;
public YoutubeVideo(String title, String linkToVideo, String thumbnailLink) {
this.title = title;
this.linkToVideo = linkToVideo;
this.thumbnailLink = thumbnailLink;
}
protected YoutubeVideo(Parcel in) {
title = in.readString();
linkToVideo = in.readString();
thumbnailLink = in.readString();
}
public static final Creator<YoutubeVideo> CREATOR = new Creator<YoutubeVideo>() {
#Override
public YoutubeVideo createFromParcel(Parcel in) {
return new YoutubeVideo(in);
}
#Override
public YoutubeVideo[] newArray(int size) {
return new YoutubeVideo[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLinkToVideo() {
String newLink;
if (linkToVideo.contains(" ")) {
newLink = linkToVideo.replaceAll(" ", "");
return newLink;
}
return linkToVideo;
}
public void setLinkToVideo(String linkToVideo) {
this.linkToVideo = linkToVideo;
}
public String getThumbnailLink() {
String fixedThumb=thumbnailLink;
if (thumbnailLink.contains(" ")) {
fixedThumb = thumbnailLink.replaceAll(" ", "");
return fixedThumb;
}
return thumbnailLink;
}
public void setThumbnailLink(String thumbnailLink) {
this.thumbnailLink = thumbnailLink;
}
#Override
public String toString() {
return "YoutubeVideo{" +
"title='" + getTitle() + '\'' +
", linkToVideo='" + getLinkToVideo() + '\'' +
", thumbnailLink='" + getThumbnailLink() + '\'' +
'}';
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(linkToVideo);
dest.writeString(thumbnailLink);
}
}
the adapter:
public class PlaylistAdapter extends
ExpandableRecyclerViewAdapter<PlaylistViewHolder, VideoViewHolder> {
public PlaylistAdapter(List<? extends ExpandableGroup> groups) {
super(groups);
}
#Override
public PlaylistViewHolder onCreateGroupViewHolder(ViewGroup parent, int
viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.playlist_item,
parent, false);
return new PlaylistViewHolder(view);
}
#Override
public VideoViewHolder onCreateChildViewHolder(ViewGroup parent, int
viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.video_item,
parent,
false);
return new VideoViewHolder(view);
}
#Override
public void onBindChildViewHolder(VideoViewHolder holder, int flatPosition,
ExpandableGroup group, int childIndex) {
YoutubeVideo video = (YoutubeVideo) group.getItems().get(childIndex);
holder.onBind(video);
}
#Override
public void onBindGroupViewHolder(PlaylistViewHolder holder, int
flatPosition, ExpandableGroup group) {
holder.setCurrentPlaylist((YoutubePlaylist) group);
}
}
main activity:
public class MainActivity extends AppCompatActivity {
RecyclerView videoListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetJsonFromUrl getJsonService = RetrofitInstance.getRetrofitInstance().create(GetJsonFromUrl.class);
Call<JsonObject> call = getJsonService.getJSON();
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if(response.isSuccessful()){
JsonArray array = response.body().getAsJsonArray("Playlists");
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<YoutubePlaylist>>(){}.getType();
ArrayList<YoutubePlaylist> youtubePlay = gson.fromJson(array, type);
for(YoutubePlaylist playlist : youtubePlay){
ArrayList<YoutubeVideo> videos = playlist.getVideos();
Log.e("###",videos.toString());
}
setArrayToAdapter(youtubePlay);
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
}
});
}
private void setArrayToAdapter(ArrayList<YoutubePlaylist> youtubePlay) {
videoListView = findViewById(R.id.videosView);
LinearLayoutManager manager = new LinearLayoutManager(this);
PlaylistAdapter adapter = new PlaylistAdapter(youtubePlay);
videoListView.setLayoutManager(manager);
videoListView.setAdapter(adapter);
}
}
playlist object output example:
YoutubePlaylist{title='Zen Work Music', videos=[YoutubeVideo{title='HEALING ZEN Music', linkToVideo='https://www.youtube.com/watch?v=SbCpzWMWb68', thumbnailLink='https://i.ytimg.com/vi_webp/SbCpzWMWb68/mqdefault.webp'}, YoutubeVideo{title='Relaxing Music - Meditation', linkToVideo='https://www.youtube.com/watch?v=qrx1vyvtRLY', thumbnailLink='https://i.ytimg.com/vi_webp/qrx1vyvtRLY/mqdefault.webp'}, YoutubeVideo{title='Relaxing Music - Background', linkToVideo='https://www.youtube.com/watch?v=loIZy6GqhUw', thumbnailLink='https://i.ytimg.com/vi_webp/loIZy6GqhUw/mqdefault.webp'}, YoutubeVideo{title='Delta Waves Sleep Music', linkToVideo='https://www.youtube.com/watch?v=EshmcHB3yMg', thumbnailLink='https://i.ytimg.com/vi_webp/EshmcHB3yMg/mqdefault.webp'}]}
im getting the groups binded and shown on list, but nothing happens onClick and i did'nt see anything regarding onClickListener in the documentation.
Thanks in advance!
The issue with this is that from the documentation here you don't have to pass your custom model YoutubePlaylist.java as a parameter as you did rather you replace it with ExpandableGroup so for your code
public class PlaylistViewHolder extends GroupViewHolder {
private TextView mPlaylistName, mPlaylistCount;
private ImageView arrow;
ExpandableListView.OnGroupClickListener listener;
public PlaylistViewHolder(View itemView) {
super(itemView);
mPlaylistName = itemView.findViewById(R.id.playlistNameView);
mPlaylistCount = itemView.findViewById(R.id.videosCount);
arrow = itemView.findViewById(R.id.expandBtn);
}
public void setCurrentPlaylist(ExpandableGroup playlist){
//the parameter has to be ExpandableGroup class and you can only get title
Log.e("###",playlist.getTitle());//you must call the getTitle() method
mPlaylistName.setText(playlist.getListTitle());
mPlaylistCount.setText("5");
}
}
This could be the way it was built. maybe a workaround this may be for
this method to then accept two parameters which is the ExpandableGroup
class and the custom model, class
public void setCurrentPlaylist(ExpandableGroup playlist, YoutubePlaylist playlist2){
//the parameter has to be ExpandableGroup class and you can only get title
Log.e("###",playlist.getTitle());//you must call the getTitle() method
mPlaylistName.setText(playlist2.getListTitle());
mPlaylistCount.setText("5");
}
In my application I want use two recyclerView into one Activity.
I want when click on items of one of this recylerView's items , add item to another recyclerView.
I write below codes, when click on items just add lasted item info to another recyclerView.
But I want when click on each items, add this each items into another recyclerView not just add lasted items.
Now just add lasted items, but I want click each item add this item.
My Activity code:
public class SuggestFilmActivity extends AppCompatActivity implements SuggestedListener {
#BindView(R.id.toolbarTitleTxt)
TextView toolbarTitleTxt;
#BindView(R.id.suggestFilm_searchEditText)
EditText suggestFilm_searchEditText;
#BindView(R.id.suggestFilm_searchBtn)
ImageView suggestFilm_searchBtn;
#BindView(R.id.suggestFilm_recyclerView)
RecyclerView suggestFilm_recyclerView;
#BindView(R.id.suggestFilm_recyclerViewProgress)
ProgressBar suggestFilm_recyclerViewProgress;
#BindView(R.id.newsPageLoadLay)
RelativeLayout newsPageLoadLay;
#BindView(R.id.suggestFilm_recyclerViewSendUser)
RecyclerView suggestFilm_recyclerViewSendUser;
private Context context;
private SuggestFilmAdapter suggestFilmAdapter;
private SuggestFilmUserAdapter suggestFilmUserAdapter;
private List<Result> model = new ArrayList<>();
private InterfaceApi api;
private SharedPrefrencesHandler prefrencesHandler;
private String token;
private GridLayoutManager gridLayoutManager;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_suggest_film);
//Initialize
ButterKnife.bind(this);
context = this;
prefrencesHandler = new SharedPrefrencesHandler(context);
api = ApiClient.getClient().create(InterfaceApi.class);
suggestFilmAdapter = new SuggestFilmAdapter(context, model, this);
gridLayoutManager = new GridLayoutManager(context, 3);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
//Get token
token = prefrencesHandler.getFromShared(SharedPrefrencesKeys.TOKEN.name());
//Set toolbar title
toolbarTitleTxt.setText(context.getResources().getString(R.string.SuggestToFollowers));
//Init followers recyclerView
suggestFilm_recyclerView.setLayoutManager(gridLayoutManager);
suggestFilm_recyclerView.setHasFixedSize(true);
//Init send user recyclerView
suggestFilm_recyclerViewSendUser.setLayoutManager(linearLayoutManager);
suggestFilm_recyclerViewSendUser.setHasFixedSize(true);
//Load more
newsPageLoadLay.setVisibility(View.GONE);
suggestFilm_recyclerView.setOnScrollListener(new EndlessRecyclerGridPage1(gridLayoutManager) {
#Override
public void onLoadMore(int current_page) {
newsPageLoadLay.setVisibility(View.VISIBLE);
Call<SeriesWhoWatchedResponse> call = api.getSuggestFilmUsers(token, filmSendData(current_page));
call.enqueue(new Callback<SeriesWhoWatchedResponse>() {
#Override
public void onResponse(Call<SeriesWhoWatchedResponse> call, Response<SeriesWhoWatchedResponse> response) {
if (response.body().getData() != null && response.body().getStatusCode() != 401
&& response.body().getStatusCode() != 402) {
if (response.body().getData().getResult().size() > 0) {
suggestFilmAdapter.addNewItem(response.body().getData().getResult());
//Gone no explore
newsPageLoadLay.setVisibility(View.GONE);
}
} else {
prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
startActivity(new Intent(context, LoginActivity.class));
}
newsPageLoadLay.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SeriesWhoWatchedResponse> call, Throwable t) {
newsPageLoadLay.setVisibility(View.GONE);
}
});
}
});
//Get user data
getUserData();
}
private void getUserData() {
suggestFilm_recyclerViewProgress.setVisibility(View.VISIBLE);
Call<SeriesWhoWatchedResponse> call = api.getSuggestFilmUsers(token, filmSendData(1));
call.enqueue(new Callback<SeriesWhoWatchedResponse>() {
#Override
public void onResponse(Call<SeriesWhoWatchedResponse> call, Response<SeriesWhoWatchedResponse> response) {
if (response.body().getData() != null && response.body().getData().getResult().size() > 0
&& response.body().getStatusCode() != 401 && response.body().getStatusCode() != 402) {
model.clear();
model.addAll(response.body().getData().getResult());
suggestFilmAdapter.notifyDataSetChanged();
suggestFilm_recyclerView.setAdapter(suggestFilmAdapter);
} else {
prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
startActivity(new Intent(context, LoginActivity.class));
}
suggestFilm_recyclerViewProgress.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SeriesWhoWatchedResponse> call, Throwable t) {
suggestFilm_recyclerViewProgress.setVisibility(View.GONE);
}
});
}
private SuggestFilmSendData filmSendData(int page) {
SuggestFilmSendData sendData = new SuggestFilmSendData();
sendData.setKeyword("");
sendData.setPageIndex(page);
sendData.setPageSize(10);
return sendData;
}
private ArrayList<SuggestFilmAddUser> prepareData(int id, String name, String image) {
ArrayList<SuggestFilmAddUser> suggestFilmAddUserList = new ArrayList<>();
SuggestFilmAddUser suggestFilmAddUser = new SuggestFilmAddUser();
suggestFilmAddUser.setId(id);
suggestFilmAddUser.setName(name);
suggestFilmAddUser.setImage(image);
suggestFilmAddUserList.add(suggestFilmAddUser);
return suggestFilmAddUserList;
}
#Override
public void onSend(int Id, String name, String image) {
ArrayList<SuggestFilmAddUser> suggestFilmAddUserList = prepareData(Id, name, image);
suggestFilmUserAdapter = new SuggestFilmUserAdapter(context, suggestFilmAddUserList);
suggestFilm_recyclerViewSendUser.setAdapter(suggestFilmUserAdapter);
}
}
One recyclerView adapter and send data Interface codes:
public class SuggestFilmAdapter extends RecyclerView.Adapter<SuggestFilmAdapter.ViewHolder> {
private Context context;
private List<Result> model;
private SuggestedListener suggestedListener;
public SuggestFilmAdapter(Context context, List<Result> model, SuggestedListener suggestedListener) {
this.context = context;
this.model = model;
this.suggestedListener = suggestedListener;
}
#Override
public SuggestFilmAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_suggest_film_users_followers, parent, false);
return new SuggestFilmAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final SuggestFilmAdapter.ViewHolder holder, final int position) {
//Name
holder.row_suggestFilmProfileName.setText(model.get(position).getName());
//Image
Glide.with(context)
.load(model.get(position).getImageUrl())
.asBitmap()
.placeholder(R.drawable.default_image)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(300, 300)
.into(new BitmapImageViewTarget(holder.row_suggestFilmProfileImage) {
#Override
protected void setResource(Bitmap resource) {
if (context == null) return;
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
holder.row_suggestFilmProfileImage.setImageDrawable(circularBitmapDrawable);
}
});
//Is Mutual
if (model.get(position).getIsMutual()) {
holder.row_suggestFilmIsOk.setVisibility(View.VISIBLE);
} else {
holder.row_suggestFilmIsOk.setVisibility(View.GONE);
}
holder.row_suggestedLay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
suggestedListener.onSend(model.get(position).getUserId(),
model.get(position).getName(),
model.get(position).getImageUrl());
}
});
}
#Override
public int getItemCount() {
return model.size();
}
public void addNewItem(List<Result> newContent) {
int start = this.model.size();
int end = newContent.size();
model.addAll(newContent);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView row_suggestFilmProfileImage, row_suggestFilmIsOk;
private TextView row_suggestFilmProfileName;
private RelativeLayout row_suggestedLay;
public ViewHolder(View itemView) {
super(itemView);
row_suggestFilmProfileImage = (ImageView) itemView.findViewById(R.id.row_suggestFilmProfileImage);
row_suggestFilmIsOk = (ImageView) itemView.findViewById(R.id.row_suggestFilmIsOk);
row_suggestFilmProfileName = (TextView) itemView.findViewById(R.id.row_suggestFilmProfileName);
row_suggestedLay = (RelativeLayout) itemView.findViewById(R.id.row_suggestedLay);
}
}
}
Model class :
public class SuggestFilmAddUser {
private int id;
private String name;
private String image;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
How can I it? Please help me
Inside onSend() , you need to add each objects to an arraylist which should be declared globally. Then call notifyItemInserted(arraylist.size()-1) in adapter to refresh recyclerview
public class SuggestFilmActivity ....
{ ArrayList<SuggestFilmAddUser> suggestFilmAddUserList=new ArrayList();
SuggestFilmUserAdapter suggestFilmUserAdapter;
......
......
protected void onCreate(Bundle savedInstance)
{....
....
....
suggestFilmUserAdapter = new SuggestFilmUserAdapter(context,
suggestFilmAddUserList);
suggestFilm_recyclerViewSendUser.setAdapter(suggestFilmUserAdapter);
.....
.....
}
public void onSend(int Id, String name, String image) {
SuggestFilmAddUser suggestFilmAddUser = new SuggestFilmAddUser();
suggestFilmAddUser.setId(id);
suggestFilmAddUser.setName(name);
suggestFilmAddUser.setImage(image);
suggestFilmAddUserList.add(suggestFilmAddUser);
suggestFilmUserAdapter.notifyItemInserted(suggestFilmAddUserList.size()-1)
}
I want to build a movie app that consumes a REST api using retrofit and displays images using Picasso and bring in Retrofit and show real movie posters as well as detail information for each movie.
i'm using The Movie Database Api to get some real data into our app. Checkout their documentation and get familiar with their API, specially the movies/popular endpoint
But when running the application white screen showing pictures does not show movies and I do not know where is the problem
this MainActivity :
package com.walkatheri.movies;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import retrofit.Callback;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
RecyclerView mRecyclerView;
final MoviesAdapter mAdapter;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mAdapter = new MoviesAdapter(this);
mRecyclerView.setAdapter(mAdapter);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://api.themoviedb.org/3")
.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addEncodedQueryParam("api_key", "MY _KEY");
}
})
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
MoviesApiService service = restAdapter.create(MoviesApiService.class);
service.getPopularMovies(new Callback<Movies.MovieResult>() {
#Override
public void success(Movies.MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
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> {
List<Movies>MovieList ;
private LayoutInflater mInflater;
private Context mContext;
public MoviesAdapter(Context context)
{
this.mContext = context;
this.mInflater = LayoutInflater.from(context);
this.MovieList = new ArrayList<>();
}
public void setMovieList(List<Movies> movieList)
{
this.MovieList=movieList ;
// The adapter needs to know that the data has changed. If we don't call this, app will crash.
notifyDataSetChanged();
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.row_movie, parent, false);
MovieViewHolder viewHolder = new MovieViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Movies movies = MovieList.get(position);
Picasso.with(mContext)
.load(movies.getPoster()).placeholder(R.color.colorAccent)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return (MovieList == null) ? 0 : MovieList.size();
}
}
}
Movies class :
package com.walkatheri.movies;
import android.graphics.Movie;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by waad on 08/10/2016.
*/
public class Movies {
private String title;
#SerializedName("poster_path")
private String poster;
#SerializedName("overview")
private String description;
#SerializedName("backdrop_path")
private String backdrop;
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 String getPoster() {
// return "http://t2.gstatic.com/images?q=tbn:ANd9GcQW3LbpT94mtUG1PZIIzJNxmFX399wr_NcvoppJ82k7z99Hx6in";
// }
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 backdrop;
}
public void setBackdrop(String backdrop) {
this.backdrop = backdrop;
}
public static class MovieResult {
private List<Movies> resulte;
public List<Movies> getResults() {
return resulte;
}
}}
MoviesApiService class:
package com.walkatheri.movies;
import retrofit.Callback;
import retrofit.http.GET;
/**
* Created by waad on 18/10/2016.
*/
public interface MoviesApiService {
#GET("/movie/popular")
void getPopularMovies(Callback<Movies.MovieResult>cb);
}
Very difficult to point out mistakes without any hint like stacktraces.
Some pointers
Use retrofit asynchronous call.
You need .addConverterFactory(GsonConverterFactory.create()) to convert json to pojos.
Image will be loaded only if you us the url http://image.tmdb.org/t/p/w185"+"yourposterpath". Check the moviedb link
Update your libs and change your api accordingly (Recommended)
Lastly a clean architecture will help you write tests properly. Your code is unstructured and you need to separate components properly. Suggest you read about MVP or MVVM patterns. Dagger can also help.
A good read about retrofit https://inthecheesefactory.com/blog/retrofit-2.0/en
So the changes
public class TestActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
public static final String MOVIE_DB_API_URL = "http://api.themoviedb.org/3/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mAdapter = new MoviesAdapter(this);
mRecyclerView.setAdapter(mAdapter);
final OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15,TimeUnit.SECONDS)
.build();
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(MOVIE_DB_API_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
MoviesApiService service = restAdapter.create(MoviesApiService.class);
Call<MoviesList> movieResultCallback = service.getPopularMovies();
// asynchronous call
movieResultCallback.enqueue(new Callback<MoviesList>() {
#Override
public void onResponse(Call<MoviesList> call, Response<MoviesList> response) {
//int code = response.code();
// can check the status code
mAdapter.setMovieList(response.body().getResults());
}
#Override
public void onFailure(Call<MoviesList> call, Throwable t) {
}
});
}
public static class MovieViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public MovieViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image);
}
}
public static class MoviesAdapter extends RecyclerView.Adapter<MovieViewHolder> {
List<Movies>MovieList ;
private LayoutInflater mInflater;
private Context mContext;
public MoviesAdapter(Context context)
{
this.mContext = context;
this.mInflater = LayoutInflater.from(context);
this.MovieList = new ArrayList<>();
}
public void setMovieList(List<Movies> movieList)
{
this.MovieList=movieList ;
// The adapter needs to know that the data has changed. If we don't call this, app will crash.
notifyDataSetChanged();
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.row, parent, false);
MovieViewHolder viewHolder = new MovieViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Movies movies = MovieList.get(position);
Picasso.with(mContext)
.load("http://image.tmdb.org/t/p/w185"+movies.getPoster_path()).placeholder(R.color.colorAccent)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return (MovieList == null) ? 0 : MovieList.size();
}
}
public static class LoggingInterceptor implements Interceptor {
#Override public okhttp3.Response intercept(Chain chain) throws IOException {
HttpUrl url = chain.request().url()
.newBuilder()
.addQueryParameter("api_key", "4848b32592990671646565fa3240a7bc")
.build();
Request request = chain.request().newBuilder().url(url).build();;
long t1 = System.nanoTime();
String requestLog = String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers());
//YLog.d(String.format("Sending request %s on %s%n%s",
// request.url(), chain.connection(), request.headers()));
if(request.method().compareToIgnoreCase("post")==0){
requestLog ="\n"+requestLog+"\n"+bodyToString(request);
}
Log.d("TAG","request"+"\n"+requestLog);
okhttp3.Response response = chain.proceed(request);
long t2 = System.nanoTime();
String responseLog = String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers());
String bodyString = response.body().string();
Log.d("TAG","response"+"\n"+responseLog+"\n"+bodyString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), bodyString))
.build();
//return response;
}
}
private static String bodyToString(final Request request) {
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
if (copy != null && copy.body() != null) // make sure its not null to avoif NPE
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e) {
return "did not work";
}
}
}
Then
public interface MoviesApiService {
#GET("movie/popular")
Call<MoviesList> getPopularMovies();
}
My Model classes
Use http://www.jsonschema2pojo.org/ to convert json to pojo
I copied the below for one the respositories on github.
Lots of similar repositories avaiable on github. https://github.com/ewintory/udacity-popular-movies and many more..
public class Movies implements Parcelable {
private int id,vote_count,favourite,reviewsaved,trailersaved;
private float vote_average,popularity;
private String original_language,original_title,overview,release_date,poster_path,title,generids,backdrop_path;
private boolean video,favored;
public Movies()
{
}
public void setReviewsaved(int reviewsaved) {
this.reviewsaved = reviewsaved;
}
public void setTrailersaved(int trailersaved) {
this.trailersaved = trailersaved;
}
public int getTrailersaved() {
return trailersaved;
}
public int getReviewsaved() {
return reviewsaved;
}
public void setFavored(boolean favored) {
this.favored = favored;
}
public void setId(int id) {
this.id = id;
}
public void setVote_count(int vote_count) {
this.vote_count = vote_count;
}
public void setFavourite(int favourite) {
this.favourite = favourite;
}
public void setVote_average(float vote_average) {
this.vote_average = vote_average;
}
public void setOriginal_language(String original_language) {
this.original_language = original_language;
}
public void setOriginal_title(String original_title) {
this.original_title = original_title;
}
public void setOverview(String overview) {
this.overview = overview;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public void setPoster_path(String poster_path) {
this.poster_path = poster_path;
}
public void setPopularity(float popularity) {
this.popularity = popularity;
}
public void setTitle(String title) {
this.title = title;
}
public void setGenerids(String generids) {
this.generids = generids;
}
public void setbackdrop_path(String backdrop_path) {
this.backdrop_path = backdrop_path;
}
public void setVideo(boolean video) {
this.video = video;
}
public String getGenerids() {
return generids;
}
public int getId() {
return id;
}
public int getVote_count() {
return vote_count;
}
public float getVote_avarage() {
return vote_average;
}
public String getOriginal_language() {
return original_language;
}
public String getOriginal_title() {
return original_title;
}
public String getOverview() {
return overview;
}
public String getRelease_date() {
return release_date;
}
public String getBackdrop_path() {
return backdrop_path;
}
public int getFavourtite() {
return favourite;
}
public String getPoster_path() {
return poster_path;
}
public float getPopularity() {
return popularity;
}
public String getTitle() {
return title;
}
public boolean isVideo() {
return video;
}
// Parcelling part
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.original_language);
dest.writeString(this.original_title);
dest.writeString(this.overview);
dest.writeString(this.poster_path);
dest.writeString(this.generids);
dest.writeString(this.title);
dest.writeString(this.release_date);
dest.writeString(this.backdrop_path);
dest.writeInt(this.favourite);
dest.writeInt(this.id);
dest.writeInt(this.vote_count);
dest.writeFloat(this.vote_average);
dest.writeFloat(this.popularity);
}
protected Movies(Parcel in) {
this.original_language = in.readString();
this.original_title = in.readString();
this.overview = in.readString();
this.poster_path = in.readString();
this.generids = in.readString();
this.title = in.readString();
this.release_date = in.readString();
this.backdrop_path = in.readString();
this.favourite = in.readInt();
this.id = in.readInt();
this.vote_count = in.readInt();
this.vote_average =in.readFloat();
this.popularity = in.readFloat();
}
public static final Creator<Movies> CREATOR = new Creator<Movies>() {
public Movies createFromParcel(Parcel source) {
return new Movies(source);
}
public Movies[] newArray(int size) {
return new Movies[size];
}
};
#Override
public int describeContents() {
return 0;
}
}
MoviesList
public class MoviesList {
private int total_pages;
public int getTotal_pages() {
return total_pages;
}
private ArrayList<Movies> results;
public ArrayList<Movies> getResults() {
return results;
}
}
Finally updated libs
// Okhttp
compile 'com.squareup.okhttp3:okhttp:3.4.1'
//Retrofit and adapters
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.picasso:picasso:2.5.2'
You can check your logs
It's almost impossible to know for sure what's going on, given your vague input, but my bet would be that you haven't specified internet permission in app's manifest:
<uses-permission android:name="android.permission.INTERNET"/>
(in src/main/AndroidManifest.xml, under manifest tag)