Firebase PagerAdapter Android - android

I am trying to use Firebase Android with a PagerAdapter, but can't seem to find a way to get the data and the child elements from firebase to my pager adapter. Does anyone have some ideas?
Here is my Firebase Data
[ {
"author" : "Rav",
"content" : "This",
"id" : 33,
"image" : "https://firebasestorage.googleapis.com/",
"timestamp" : "13892733894"
}, {
"author" : "Mihail",
"content" : "blalala",
"id" : 44,
"image" : "https://firebasestorage.googleapis.com/",
"timestamp" : 241414212
}]
I am using this PagerAdapter and trying to get the images to it:
public class NovAdapter extends PagerAdapter {
private Context mContext;
private LayoutInflater mLayoutInflater;
private final Utils.LibraryObject[] LIBRARIES = new Utils.LibraryObject[]{
new Utils.LibraryObject(
R.drawable.img_one,
"Лако"),
new Utils.LibraryObject(
R.drawable.img_two,
"Гро"),
new Utils.LibraryObject(
R.drawable.img_tree,
"Ков"),
new Utils.LibraryObject(
R.drawable.img_four,
"Шеф")
};
public NovAdapter(final Context context) {
mContext = context;
mLayoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return LIBRARIES.length;
}
#Override
public int getItemPosition(final Object object) {
return POSITION_NONE;
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
View view = null;
final ViewHolder holder;
if (view == null) {
view = mLayoutInflater.inflate(R.layout.item, container, false);
holder = new ViewHolder();
holder.img = (ImageView) view.findViewById(R.id.img_item);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
final Utils.LibraryObject libraryObject = LIBRARIES[position];
Picasso.with(view.getContext()).load(libraryObject.getRes()).into(holder.img);
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(mContext, String.valueOf(position) + " " + libraryObject.getGlavi(), Toast.LENGTH_SHORT).show();
}
});
container.addView(view);
return view;
}
#Override
public boolean isViewFromObject(final View view, final Object object) {
return view.equals(object);
}
#Override
public void destroyItem(final ViewGroup container, final int position, final Object object) {
container.removeView((View) object);
}
private static class ViewHolder {
ImageView img;
}
This is the class i am using
public static class LibraryObject {
private String mTitle;
private int mRes;
public LibraryObject(final int res, final String title) {
mRes = res;
mTitle = title;
}
public String getTitle() {
return mTitle;
}
public void setTitle(final String title) {
mTitle = title;
}
public int getRes() {
return mRes;
}
public void setRes(final int res) {
mRes = res;
}
}
}
And this is my Post.class
public class Posts {
private Long id;
private String author;
private String image;
public Posts(){
}
public Posts(Long id, String author, String image) {
this.id = id;
this.author = author;
this.image = image;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}

Related

Instantiate a generic adapter for RecyclerView

I am a newbie in recyclerview. I have created my generic adapter for different properties by following the #SebastienRieu's answer, i.e. This link. The problem is that I want to instantiate the adapter and set it to my recyclerview. How Do I do that?
Here, 2nd parameter is context. What should replace the 1st paramenter with?
GenericModelAdapter adapter= new GenericModelAdapter(??, this)
recyclerView.setAdapter(adapter);
Any help is appreciated.
My PostModelClass:
public class PostsModelClass {
int userId;
int id;
String title;
#SerializedName("body")
String textBody;
public int getUserId() {
return userId;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getTextBody() {
return textBody;
}
}
Similarly, here's my CommentsModelclass:
public class CommentsModelClass {
String postId;
String id;
String name;
String email;
#SerializedName("body")
String textBody;
public String getPostId() {
return postId;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getTextBody() {
return textBody;
}
And here's my adapter:
public class GenericModelAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private static final int TYPE_POSTS = 10;
private static final int TYPE_COMMENTS = 11;
private static final int TYPE_PHOTOS = 12;
private static final int TYPE_USERS = 13;
private List<GenericViewModel> mItems;
public GenericModelAdapter(List<GenericViewModel> items, Context context) {
this.mItems = items;
this.mContext = context;
}
#Override
public int getItemViewType(int position) {
GenericViewModel genericItems = mItems.get(position);
if (genericItems.isPostsModel()) {
return TYPE_POSTS;
} else if (genericItems.isCommentsModel()) {
return TYPE_COMMENTS;
} else if (genericItems.isPhotosModel()) {
return TYPE_PHOTOS;
} else {
return TYPE_USERS;
}
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
TextView textViewResult;
PostViewHolder(#NonNull View itemView) {
super(itemView);
textViewResult = itemView.findViewById(R.id.textViewResult);
}
}
public static class CommentsViewHolder extends RecyclerView.ViewHolder {
TextView textViewResult;
CommentsViewHolder(#NonNull View itemView) {
super(itemView);
textViewResult = itemView.findViewById(R.id.textViewResult);
}
}
public static class PhotosViewHolder extends RecyclerView.ViewHolder {
TextView textViewResult;
PhotosViewHolder(#NonNull View itemView) {
super(itemView);
textViewResult = itemView.findViewById(R.id.textViewResult);
}
}
public static class UsersViewHolder extends RecyclerView.ViewHolder {
TextView textViewResult;
UsersViewHolder(#NonNull View itemView) {
super(itemView);
textViewResult = itemView.findViewById(R.id.textViewResult);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
if (viewType == TYPE_POSTS) {
View rootView = inflater.inflate(R.layout.single_item, parent, false);
return new PostViewHolder(rootView);
} else if (viewType == TYPE_COMMENTS) {
View rootView = inflater.inflate(R.layout.single_item, parent, false);
return new CommentsViewHolder(rootView);
} else if (viewType == TYPE_PHOTOS) {
View rootView = inflater.inflate(R.layout.single_item, parent, false);
return new PhotosViewHolder(rootView);
} else {
View rootView = inflater.inflate(R.layout.single_item, parent, false);
return new UsersViewHolder(rootView);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
GenericViewModel genericViewModel = mItems.get(position);
if (genericViewModel.isPostsModel()) {
onBindPost(holder, genericViewModel.getPostsModelClass());
} else if (genericViewModel.isCommentsModel()) {
//onBindComments(holder, genericViewModel.getCommentsModelClass());
} else if (genericViewModel.isPhotosModel()) {
//onBindPhotos(holder, genericViewModel.getPhotosModelClass());
} else if (genericViewModel.isUsersModel()) {
//onBindUsers(holder, genericViewModel.getUsersModelClass());
}
}
private void onBindPost(RecyclerView.ViewHolder holder, PostsModelClass postsModelClass) {
String content = "User ID: " + postsModelClass.getUserId() +
"\nID: " + postsModelClass.getId() +
"\nTitle: " + postsModelClass.getTitle() +
"\nBody: " + postsModelClass.getTextBody();
((PostViewHolder) holder).textViewResult.setText(content);
}
#Override
public int getItemCount() {
return mItems.size();
}
}
And lastly, My GenericViewModel:
public class GenericViewModel {
private PostsModelClass mPostsModelClass;
private CommentsModelClass mCommentsModelClass;
private PhotosModelClass mPhotosModelClass;
private UsersModelClass mUsersModelClass;
private GenericViewModel(PostsModelClass postsModelClass, CommentsModelClass commentsModelClass, PhotosModelClass photosModelClass, UsersModelClass usersModelClass) {
this.mPostsModelClass = postsModelClass;
this.mCommentsModelClass = commentsModelClass;
this.mPhotosModelClass = photosModelClass;
this.mUsersModelClass = usersModelClass;
}
public boolean isPostsModel() {
return mPostsModelClass != null;
}
public boolean isCommentsModel() {
return mCommentsModelClass != null;
}
public boolean isPhotosModel() {
return mPhotosModelClass != null;
}
public boolean isUsersModel() {
return mUsersModelClass != null;
}
public static GenericViewModel getPostsInstance(PostsModelClass modelClass) {
return new GenericViewModel(modelClass, null, null, null);
}
public static GenericViewModel getCommentsInstance(CommentsModelClass modelClass) {
return new GenericViewModel(null, modelClass, null, null);
}
public static GenericViewModel getPhotosInstance(PhotosModelClass modelClass) {
return new GenericViewModel(null, null, modelClass, null);
}
public static GenericViewModel getUsersInstance(UsersModelClass modelClass) {
return new GenericViewModel(null, null, null, modelClass);
}
public PostsModelClass getPostsModelClass() {
return mPostsModelClass;
}
public CommentsModelClass getCommentsModelClass() {
return mCommentsModelClass;
}
public PhotosModelClass getPhotosModelClass() {
return mPhotosModelClass;
}
public UsersModelClass getUsersModelClass() {
return mUsersModelClass;
}
}
Yes, I haven't shared the model classes for Posts and Users. They are similar to these model classes and I'd implement them later.
Here's the error I'm facing:
Based on the reference you gave in the question, you need a model that contains all your different properties like EventViewModel in the link and populate the list based on the viewType.
ArrayList<EventViewModel> eventList = "YOUR LIST"
GenericModelAdapter adapter= new GenericModelAdapter(eventList, this)
It must be ArrayList of different collected properties:
GenericModelAdapter adapter= new GenericModelAdapter(ArrayList<YourModel> eventList, this)
Your model:
public class YourModel() {
private Property1 mProperty1;
private Property2 mProperty2;
private YourModel(Property1 property1, Property2 property2) {
this.mProperty1 = property1;
this.mProperty2 = property2;
}
public boolean isProperty1() {
return mProperty1 != null
}
public boolean isProperty2() {
return mProperty2 != null
}
public static YourModel getProperty1Instance(Property1 property1) {
return new YourModel(property1, null);
}
public static EventViewModel getProperty2Instance(Property1 property2) {
return new YourModel(null, property2);
}
public Property1 getProperty1() {
return mProperty1;
}
public Property2 getProperty2() {
return mProperty2;
}
}

RecyclerView with different types and different adapter

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.

Insert and update Database to last shown activity

I have a simple problem (I think), that I cannot solve, even after much research. So for the first time I decided to post. I apologize if this is basic, or I cannot explain well. I'm a beginner.
I am devoloping a project, where I must connect to a database of movies, and get information through json.
At this point, I have my app running a list of playing now movies as other lists.
My goal (and problem) now is: When offline, show the last list displayed on the screen.
For that, I must somehow save that list to a database (I've never worked with db), and delete and update to a new one whenever i change screens on my app, so that the last list is displayed when online.
After that, I must show that last saved list (updated db).
Questions: where to code for insert (update) database?
How to convert that list into a db class? I think I must do that...
How to do the otherwise to insert that in a listview?
I use the same xml for that ListView? Since have the same params I think so...
So, here part of my code for this:
Fragment
public class NowPlayingMoviesFragment extends BaseFragment{
private ListView listMovies;
private Button buttonGetMore;
private List<Movie> movieList;
private int currentPage=1;
private MovieAdapter movieAdapter;
private ListView listOfflineMovies;
public static NowPlayingMoviesFragment newInstance() {
Bundle args = new Bundle();
NowPlayingMoviesFragment fragment = new NowPlayingMoviesFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.now_playing_movies_fragment, container, false);
findViews(v);
executeNowPlayingMoviesRequest();
addListeners();
return v;
}
private void executeNowPlayingMoviesRequest() {
new GetNowPlayingMoviesAsyncTask(getActivity(), String.valueOf(currentPage), getResources().getString(R.string.language)) {
#Override
protected void onResponseSuccess(MoviesResponse moviesResponse) {
DLog.d(tag, "onResponseSuccess " + moviesResponse);
// create the adapter
if (movieAdapter != null) {
List<Movie> movies = moviesResponse.getMovies();
for (int i = 0; i < movies.size(); i++) {
movieList.add(movies.get(i));
}
movieAdapter.notifyDataSetChanged();
**//is it here i save into db??**
} else {
movieList = moviesResponse.getMovies();
movieAdapter = new MovieAdapter(getActivity(), movieList);
listMovies.setAdapter(movieAdapter);
}
}
#Override
protected void onNetworkError () {
DLog.d(tag, "onNetworkError ");
// Here i now that some error occur when processing the request,
// possible my internet connection if turned off
//OfflineMovieDbEntity();
//MoviesItemDbEntity offlineMovies = new MoviesItemDbEntity(getActivity(),Movie.getOriginalTitle());
// MoviesItemDbEntity offlineMovies = offlineMovies.findById(offLineMovies.class,1)
}
}.execute();
}
private void findViews(View v) {
listMovies = (ListView) v.findViewById(R.id.now_playing_movies_list_view);
buttonGetMore = (Button) v.findViewById(R.id.get_more_button_movies_now);
listOfflineMovies = (ListView) v.findViewById(R.id.offline_movies_screen_list_view);
}
private void addListeners() {
buttonGetMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage=currentPage+1;
executeNowPlayingMoviesRequest();
}
});
}
}
---------------------------------------------------------------
# Movie Adapter #
public class MovieAdapter extends ArrayAdapter<Movie> {
public MovieAdapter(#NonNull Context context, #NonNull List<Movie> objects) {
super(context, 0, objects);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v;
final ViewHolder holder;
final Movie item = getItem(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
v = inflater.inflate(R.layout.movie_item, parent, false);
holder = new ViewHolder(v);
v.setTag(holder);
} else {
v = convertView;
holder = (ViewHolder) v.getTag();
}
holder.movieTitle.setText(item.getTitle());
//See movie details onclick
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), MovieDetailsScreen.class);
intent.putExtra("Movie", item);
getContext().startActivity(intent);
}
});
return v;
}
static class ViewHolder {
private TextView movieTitle;
public ViewHolder(View v) {
movieTitle = (TextView) v.findViewById(R.id.movie_item_title);
}
}
}
------------------------------------------------------------------------
#movie entitie#
public class Movie implements Parcelable {
#SerializedName("poster_path")
private String posterPath;
#SerializedName("overview")
private String overview;
#SerializedName("release_date")
private String releaseDate;
#SerializedName("original_title")
private String originalTitle;
#SerializedName("original_language")
private String originalLanguage;
#SerializedName("title")
private String title;
#SerializedName("backdrop_path")
private String backdropPath;
#SerializedName("popularity")
private Double popularity;
#SerializedName("vote_count")
private Integer voteCount;
#SerializedName("vote_average")
private Double voteAverage;
public String getPosterPath() {
return posterPath;
}
public String getOverview() {
return overview;
}
public String getReleaseDate() {
return releaseDate;
}
public String getOriginalTitle() {
return originalTitle;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public String getTitle() {
return title;
}
public String getBackdropPath() {
return backdropPath;
}
public Double getPopularity() {
return popularity;
}
public Integer getVoteCount() {
return voteCount;
}
public Double getVoteAverage() {
return voteAverage;
}
public Movie() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.posterPath);
dest.writeString(this.overview);
dest.writeString(this.releaseDate);
dest.writeString(this.originalTitle);
dest.writeString(this.originalLanguage);
dest.writeString(this.title);
dest.writeString(this.backdropPath);
dest.writeValue(this.popularity);
dest.writeValue(this.voteCount);
dest.writeValue(this.voteAverage);
}
protected Movie(Parcel in) {
this.posterPath = in.readString();
this.overview = in.readString();
this.releaseDate = in.readString();
this.originalTitle = in.readString();
this.originalLanguage = in.readString();
this.title = in.readString();
this.backdropPath = in.readString();
this.popularity = (Double) in.readValue(Double.class.getClassLoader());
this.voteCount = (Integer) in.readValue(Integer.class.getClassLoader());
this.voteAverage = (Double) in.readValue(Double.class.getClassLoader());
}
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel source) {
return new Movie(source);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
-----------------------------------------------------------------
#movies response#
public class MoviesResponse {
#SerializedName("page")
private Integer page;
#SerializedName("results")
private List<Movie> movies = new ArrayList<>();
#SerializedName("total_pages")
private Integer totalPages;
public Integer getPage() {
return page;
}
public Integer getTotalPages() {
return totalPages;
}
public List<Movie> getMovies() {
return movies;
}
}
-----------------------------------------------------------
MovieAsyncTask
public abstract class GetNowPlayingMoviesAsyncTask extends ExecuteRequestAsyncTask<MoviesResponse> {
private static final String PATH = "/movie/now_playing";
private static final String LANGUAGE_KEY = "language";
private static final String PAGE_KEY = "page";
private String page;
private String language;
public GetNowPlayingMoviesAsyncTask(Context context, String page, String language) {
super(context);
this.page=page;
this.language=language;
}
#Override
protected String getPath() {
return PATH;
}
#Override
protected void addQueryParams(StringBuilder sb) {
addQueryParam(sb, LANGUAGE_KEY, language);
addQueryParam(sb, PAGE_KEY, page);
}
#Override
protected Class<MoviesResponse> getResponseEntityClass() {
return MoviesResponse.class;
}
}
-----------------------------------------
#Movie Database#
public class MoviesItemDbEntity extends SugarRecord {
public static final String TITLE_COLUMN_NAME = "movie_title_column";
private String title;
public MoviesItemDbEntity() {
}
public MoviesItemDbEntity(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public String setTitle() {
return title;
}
}
---------------------------------------------------------
#Movie Item xml#
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center_horizontal">
<TextView
android:id="#+id/movie_item_title"
style="#style/ItemListStyle"
android:text="lalalala"/>
</LinearLayout>
---------------------------------------------------------------
#now playing ListView xml#
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="#+id/now_playing_movies_title"
style="#style/TitleStyle"
android:text="#string/movies"/>
<Button
android:id="#+id/get_more_button_movies_now"
style="#style/ButtonMoreStyle"/>
<ListView
android:id="#+id/now_playing_movies_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/now_playing_movies_title">
</ListView>
</RelativeLayout>

How can i set another data into constructor DataModel in Retrofit in Android

In my application I should load data from server and for this job I use Retrofit library.
In my application i want load string data from server and i should load images from drawable folder .
I can load string from server and show it on textview, but when add images i don't know how can i it?!
DataModel:
public class Retrofit_ColoniesModel {
//Load from server
#SerializedName("id")
private Integer id;
#SerializedName("slug")
private String slug;
#SerializedName("title")
private String title;
#SerializedName("description")
private String description;
#SerializedName("parent")
private Integer parent;
#SerializedName("post_count")
private Integer post_count;
//Load from local
private int[] image;
public Retrofit_ColoniesModel(Integer id, String slug, String title, String description, Integer parent, Integer post_count,
int[] image) {
this.id = id;
this.slug = slug;
this.title = title;
this.description = description;
this.parent = parent;
this.post_count = post_count;
this.image = image;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getParent() {
return parent;
}
public void setParent(Integer parent) {
this.parent = parent;
}
public Integer getPost_count() {
return post_count;
}
public void setPost_count(Integer post_count) {
this.post_count = post_count;
}
public int[] getImage() {
return image;
}
public void setImage(int[] image) {
this.image= image;
}
DataModelResponse:
public class Retrofit_ColoniesModelResponse {
#SerializedName("status")
private String status;
#SerializedName("count")
private int count;
#SerializedName("categories")
private List<Retrofit_ColoniesModel> categories;
public List<Retrofit_ColoniesModel> getCategories() {
return categories;
}
public void setCategories(List<Retrofit_ColoniesModel> categories) {
this.categories = categories;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Retrofit code in activity:
// Retrofit //////////
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<Retrofit_ColoniesModelResponse> call = apiInterface.getResponse();
call.enqueue(new Callback<Retrofit_ColoniesModelResponse>() {
#Override
public void onResponse(Call<Retrofit_ColoniesModelResponse> call, Response<Retrofit_ColoniesModelResponse> response) {
List<Retrofit_ColoniesModel> models = response.body().getCategories();
mAdaper = new ColoniesAdapter(context, models);
colonies_RecyclerView.setAdapter(mAdaper);
}
#Override
public void onFailure(Call<Retrofit_ColoniesModelResponse> call, Throwable t) {
}
});
//////////////////////
I want save images into Array, such as :
final int[] colImages = {
R.drawable.colonies_image_food,
R.drawable.colonies_image_medical,
R.drawable.colonies_image_tecgnolegy,
R.drawable.colonies_image_entertenement,
R.drawable.colonies_image_car,
R.drawable.colonies_image_model,
R.drawable.colonies_image_sport,
};
Adapter:
public class ColoniesAdapter extends RecyclerView.Adapter<ColoniesAdapter.ViewHolder> {
private List<Retrofit_ColoniesModel> mDateSet;
private Context mContext;
private SparseBooleanArray expandState = new SparseBooleanArray();
public ColoniesAdapter(Context context, List<Retrofit_ColoniesModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
for (int i = 0; i < mDateSet.size(); i++) {
expandState.append(i, false);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.colonies_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.colonies_title.setText(mDateSet.get(position).getTitle());
holder.colonies_title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
Retrofit_ColoniesModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getTitle())
.putExtra("categoryID", model.getId()));
}
});
Glide.with(mContext)
.load(mDateSet.get(position).getImage()[position])
.placeholder(R.drawable.post_image)
.crossFade()
.override(700, 400)
.into(holder.colonies_image);
holder.colonies_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
Retrofit_ColoniesModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getTitle())
.putExtra("categoryID", model.getId()));
}
});
holder.colonies_description.setText(mDateSet.get(position).getDescription());
holder.colonies_count.setText("مطالب موجود در کلونی : " + mDateSet.get(position).getPost_count());
holder.expandableLayout.setInterpolator(mDateSet.get(position).getInterpolator());
holder.expandableLayout.setExpanded(expandState.get(position));
holder.expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
createRotateAnimator(holder.buttonLayout, 0f, 180f).start();
expandState.put(position, true);
}
#Override
public void onPreClose() {
createRotateAnimator(holder.buttonLayout, 180f, 0f).start();
expandState.put(position, false);
}
});
holder.buttonLayout.setRotation(expandState.get(position) ? 180f : 0f);
holder.buttonLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
onClickButton(holder.expandableLayout);
}
});
}
private void onClickButton(final ExpandableLayout expandableLayout) {
expandableLayout.toggle();
}
#Override
public int getItemCount() {
return mDateSet.size();
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<Retrofit_ColoniesModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<Retrofit_ColoniesModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView colonies_title, colonies_description, colonies_count;
private ImageView colonies_image;
private ExpandableLinearLayout expandableLayout;
private RelativeLayout buttonLayout;
public ViewHolder(View itemView) {
super(itemView);
colonies_title = (TextView) itemView.findViewById(R.id.colonies_colony_title_text);
colonies_image = (ImageView) itemView.findViewById(R.id.colonies_cover_image);
colonies_description = (TextView) itemView.findViewById(R.id.colonies_expandable_description_text);
colonies_count = (TextView) itemView.findViewById(R.id.colonies_count_title_text);
buttonLayout = (RelativeLayout) itemView.findViewById(R.id.colonies_expandable_button);
expandableLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.colonies_expandable_layout);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
.putExtra("title", model.getTitle())
.putExtra("image", model.getThumbnail()));*/
}
});
}
}
public ObjectAnimator createRotateAnimator(final View target, final float from, final float to) {
ObjectAnimator animator = ObjectAnimator.ofFloat(target, "rotation", from, to);
animator.setDuration(300);
animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
return animator;
}
}
I don't know how can i add int[] into my constructor, because in retrofit fill the constructor with List<Retrofit_ColoniesModel> models = response.body().getCategories(); .
How can i fix my issue? I really need this tutorial, please help me. Thanks all <3
If the array of images is static (don't depend on the server) then you could just do the following:
public class Retrofit_ColoniesModel {
...
private static final int[] colImages = {
R.drawable.colonies_image_food,
R.drawable.colonies_image_medical,
R.drawable.colonies_image_tecgnolegy,
R.drawable.colonies_image_entertenement,
R.drawable.colonies_image_car,
R.drawable.colonies_image_model,
R.drawable.colonies_image_sport,
};
But if this array is not static (depends on the server response) then I suggest you to map to an array of Strings that describe each image, and the server should respond with those Strings, for example:
"images":["IMAGE1", "IMAGE2"]
And then have a helper class that could map between those string keys to the actual R.drawable resources.
Let me know if you need sample code.
Non-static Nested Classes (Inner Classes)
Non-static nested classes in Java are also called inner classes. Inner classes are associated with an instance of the enclosing class. Thus, you must first create an instance of the enclosing class to create an instance of an inner class. Here is an example inner class definition:
public class Outer {
public class Inner {
}
}
Here is how you create an instance of the Inner class:
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
Notice how you put new after the reference to the outer class in order to create an instance of the inner class.
Non-static nested classes (inner classes) have access to the fields of the enclosing class, even if they are declared private. Here is an example of that:

Android List item displaying package name and # instead of string value

I implemented parceable class to pass some data from one activity to the other. I managed to get the rest of the items in the class. But that class has a list object i want to display in another fragment. i think the problem has to do with my adapter. kindly help me out. i have attached my fragment class and my adapter class as well.
Fragment Class
public class ForumDetailFragment extends Fragment {
private TextView titleTV;
private TextView timeTV;
private TextView dateTV;
private TextView detailsTV;
private ListView answerListView;
private LinearLayout themeLayout;
private ImageView themeIMG;
private StoredForum currentQuestion;
private AnswerAdapter adapter;
SimpleDateFormat formatDate = new SimpleDateFormat("MMM-dd-yyyy");
SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm aaa");
public ForumDetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_forum_detail, container, false);
currentQuestion = getArguments().getParcelable(StoredForum.QUESTION_CLASS);
titleTV = (TextView) rootView.findViewById(R.id.titleTV);
timeTV = (TextView) rootView.findViewById(R.id.timeTV);
detailsTV = (TextView) rootView.findViewById(R.id.detailsTV);
answerListView = (ListView) rootView.findViewById(R.id.answerListView);
themeLayout = (LinearLayout) rootView.findViewById(R.id.eventTypeThemeLayout);
themeIMG = (ImageView) rootView.findViewById(R.id.eventTypeThemeIMG);
dateTV = (TextView) rootView.findViewById(R.id.dateTV);
titleTV.setText(currentQuestion.getTitle());
detailsTV.setText(currentQuestion.getDescription());
timeTV.setText(formatTime.format(currentQuestion.getQuestionDate()));
dateTV.setText(formatDate.format(currentQuestion.getQuestionDate()));
setupTheme();
setUpListView(rootView);
updateAnswer();
return rootView;
}
public void setUpListView(View rootView) {
answerListView = (ListView) rootView.findViewById(R.id.answerListView);
adapter = new AnswerAdapter(getActivity(), new ArrayList<Question>());
answerListView.setAdapter(adapter);
}
private void setupTheme() {
if (currentQuestion.getDescription().equals(StoredForum.FORUM_QUESTION)) {
themeLayout.setBackgroundColor(getActivity().getResources().getColor(R.color.pink));
themeIMG.setImageResource(R.drawable.abc_ic_menu_copy_mtrl_am_alpha);
} else {
themeLayout.setBackgroundColor(getActivity().getResources().getColor(R.color.orange));
themeIMG.setImageResource(R.drawable.abc_ic_menu_paste_mtrl_am_alpha);
}
}
public void updateAnswer() {
AuthUser user = AuthUser.getInstance(getActivity());
Retrofit retrofit = ApiHandle.getRetrofit(user.getToken());
QuestionService service = retrofit.create(QuestionService.class);
service.getQuestions().enqueue(new Callback<List<com.apps233.moja.packages.forum.Question>>() {
#Override
public void onResponse(Response<List<com.apps233.moja.packages.forum.Question>> response, Retrofit retrofit) {
if (response.isSuccess()) {
adapter.clear();
adapter.addAll(response.body());
adapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
Adapter Class
public class AnswerAdapter extends ArrayAdapter<Question> {
List<Question> answers = new ArrayList<Question>();
public AnswerAdapter(Context context, List<Question> answers) {
super(context, R.layout.item_answer, answers);
this.answers = answers;
}
public static class ViewHolder {
private TextView titleTV;
private TextView descriptionTV;
public ViewHolder(View view) {
titleTV = (TextView) view.findViewById(R.id.titleTV);
descriptionTV = (TextView) view.findViewById(R.id.descriptionTV);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Question question = answers.get(position);
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_answer, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleTV.setText("Doctor");
holder.descriptionTV.setText(question.getAnswers().toString());
return convertView;
}
}
The list is displayed in the activity below
the list is displaying the package name # some list of numbers
Question Class
public class Question {
private Long id;
private String title;
private Long userId;
private String description;
private Date questionDate;
private List<Answer> answers;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getQuestionDate() {
return questionDate;
}
public void setQuestionDate(Date questionDate) {
this.questionDate = questionDate;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers (List<Answer> answers){
this.answers = answers;
}
}
Parceable Class
public class StoredForum implements Parcelable {
public static final String QUESTION_ID = "QUESTION_ID";
public static final String QUESTION_CLASS = "QUESTION";
public static final String FORUM_QUESTION = "forum-chat";
Long id;
Long userId;
String title;
String description;
Date questionDate;
List<Answer> answers;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getQuestionDate() {
return questionDate;
}
public void setQuestionDate(Date questionDate) {
this.questionDate = questionDate;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers){
this.answers = answers;
}
private StoredForum() {
}
public static StoredForum fromQuestion(Question question) {
StoredForum storedForum = new StoredForum();
storedForum.setId(question.getId());
storedForum.setUserId(question.getUserId());
storedForum.setTitle(question.getTitle());
storedForum.setDescription(question.getDescription());
storedForum.setQuestionDate(question.getQuestionDate());
storedForum.setAnswers(question.getAnswers());
return storedForum;
}
protected StoredForum(Parcel in) {
id = in.readByte() == 0x00 ? null : in.readLong();
userId = in.readByte() == 0x00 ? null : in.readLong();
title = in.readString();
description = in.readString();
questionDate = new Date(in.readString());
answers = new ArrayList<Answer>();
answers = in.readArrayList(Answer.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (id == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeLong(id);
}
if (userId == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeLong(userId);
}
dest.writeString(title);
dest.writeString(description);
if(questionDate != null){
dest.writeString(questionDate.toString());
} else {
dest.writeString("0");
}
answers = new ArrayList<Answer>();
dest.writeList(answers);
}
public static final Parcelable.Creator<StoredForum> CREATOR = new Parcelable.Creator<StoredForum>() {
#Override
public StoredForum createFromParcel(Parcel in) {
return new StoredForum(in);
}
#Override
public StoredForum[] newArray(int size) {
return new StoredForum[size];
}
};
}
Answer Class
public class Answer {
Long id;
Long userId;
Long questionId;
String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getQuestionId() {
return questionId;
}
public void setQuestionId(Long questionId) {
this.questionId = questionId;
}
public String getDescription() {
return description;
}
public void setDescription(String description){
this.description = description;
}
}
You need to implement/override public String toString() method in Answer class.
#Override
public String toString() {
return description;
}

Categories

Resources