How to implement parent-child Recyclerview on Android - java

can you give me some reference about parent-child recycleview? i have successfully made parent-Recycleview but i'm stuck to pass child-Recycleview when im clicked item from parent
NB: i'm use dummy data
This is example of recyclerview I want to create:
and this is my code
RecycleParentAdapter.java
public class RecycleParentMenuAdapter extends RecyclerView.Adapter<RecycleParentMenuAdapter.ViewHolder>{
private ArrayList<Store> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
public RecycleParentMenuAdapter(ArrayList<Store> mData, Context context) {
this.mData = mData;
this.mInflater = LayoutInflater.from(context);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = mInflater.from(viewGroup.getContext()).inflate(R.layout.list_store_lists, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.storeName.setText(mData.get(position).getName());
// holder.storeImage.setImageURI(mData.get(position).getImage());
}
#Override
public int getItemCount() {
return (mData != null) ? mData.size() : 0;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private CircleImageView storeImage;
private TextView storeName;
ViewHolder(View itemView) {
super(itemView);
storeImage = itemView.findViewById(R.id.ivListStoreImage);
storeName = itemView.findViewById(R.id.tvListStoreName);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) {
mClickListener.onItemClick(view, getAdapterPosition());
}
}
}
public int getItem(int id) {
return (mData != null) ? mData.size() : 0;
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
RecycleChildAdapter.java
public class RecycleChildMenuAdapter extends RecyclerView.Adapter<RecycleChildMenuAdapter.ViewHolder> {
// private String[] mData;
private ArrayList<Menu> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
public RecycleChildMenuAdapter(ArrayList<Menu> mData, Context context) {
this.mData = mData;
this.mInflater = LayoutInflater.from(context);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = mInflater.from(viewGroup.getContext()).inflate(R.layout.list_menu_lists, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
// viewHolder.myTextView.setText(mData.get(i).get);
// viewHolder.id.setText((int) 12l);
viewHolder.menuName.setText(mData.get(i).getName());
// viewHolder.menuImage.setText(mData.get(i).getImage());
}
#Override
public int getItemCount() {
return (mData != null) ? mData.size() : 0;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView menuName;
private CircleImageView menuImage;
private TextView id;
ViewHolder(View itemView) {
super(itemView);
menuName = itemView.findViewById(R.id.tvListMenuName);
menuImage = itemView.findViewById(R.id.ivListMenuImage);
// myTextView = itemView.findViewById(R.id.info_text);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) {
mClickListener.onItemClick(view, getAdapterPosition());
}
}
}
public int getItem(int id) {
return (mData != null) ? mData.size() : 0;
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
fragment.java
public class DineinFragment extends Fragment implements RecycleParentMenuAdapter.ItemClickListener,RecycleChildMenuAdapter.ItemClickListener, CustomToolbar {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
RecycleParentMenuAdapter storeAdapter;
private ArrayList<Store> storeArrayList;
public RecycleChildMenuAdapter menuAdapter;
public ArrayList<Menu> menuArrayList;
private TextView toolbarTitle;
private ImageView btnBackToolbar;
private TextView titleStore;
private OnFragmentInteractionListener mListener;
public DineinFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static DineinFragment newInstance(String param1, String param2) {
DineinFragment fragment = new DineinFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dinein, container, false);
// View v = inflater.inflate(R.layout.list_store_lists, container, false);
setCustomToolbar(view);
addStore();
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rvStoreList);
storeAdapter = new RecycleParentMenuAdapter(storeArrayList, getActivity());
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
storeAdapter.setClickListener(this);
recyclerView.setAdapter(storeAdapter);
// titleStore = (TextView) v.findViewById(R.id.tvListStoreName);
// titleStore.setText();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(View view, int position) {
}
#Override
public void setCustomToolbar(View view) {
btnBackToolbar = (ImageView) view.findViewById(R.id.ivBackToolbar);
toolbarTitle = (TextView) view.findViewById(R.id.tvTitleToolbar);
toolbarTitle.setText("Menu");
btnBackToolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.test));
}
});
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public void addStore() {
storeArrayList = new ArrayList<>();
storeArrayList.add(new Store("1", "Toko A", "www"));
storeArrayList.add(new Store("2", "Toko B", "www"));
storeArrayList.add(new Store("3", "Toko C", "www"));
storeArrayList.add(new Store("4", "Toko D", "www"));
}
public void addData() {
menuArrayList = new ArrayList<>();
menuArrayList.add(new Menu("1", "Sate Ayam", "Lorem", "www", 13500, "4"));
menuArrayList.add(new Menu("2", "Ayam Goreng", "Lorem ayam", "www", 17000, "1"));
menuArrayList.add(new Menu("3", "Sate Kambing", "Lorem sate", "www", 18000, "1"));
menuArrayList.add(new Menu("4", "Ikan Bakar", "Lorem ikan", "www", 7500, "7"));
menuArrayList.add(new Menu("5", "Udang Goreng", "Lorem udang", "www", 23350, "2"));
menuArrayList.add(new Menu("6", "Mie Goreng Aceh", "Lorem mie", "www", 18000, "9"));
menuArrayList.add(new Menu("7", "Fuyunghai", "Lorem fuyunghai", "www", 25000, "1"));
menuArrayList.add(new Menu("8", "Nasi Gila", "Lorem Nasi Gila", "www", 16000, "4"));
menuArrayList.add(new Menu("9", "Rawon Setan", "Lorem rawon", "www", 23000, "3"));
menuArrayList.add(new Menu("10", "Ayam Tepung", "Lorem ayam tepung", "www", 22000, "6"));
menuArrayList.add(new Menu("11", "Ikan Tepung", "Lorem ikan tepung", "www", 32000, "8"));
menuArrayList.add(new Menu("12", "Udang Tepung", "Lorem udang tepung", "www", 37500, "8"));
menuArrayList.add(new Menu("13", "Cumi Goreng", "Lorem cumi goreng", "www", 32100, "5"));
}
}
StoreModel.java
public class Store {
private String id;
private String name;
private String image;
public Store(String id, String name, String image) {
this.id = id;
this.name = name;
this.image = image;
}
public Store() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
MenuModel.java
package com.snoci.resto.util.model;
public class Menu {
private String id;
private String name;
private String desc;
private String image;
private Number price;
private String storeId;
public Menu(String id, String name, String desc, String image, Number price, String storeId) {
this.id = id;
this.name = name;
this.desc = desc;
this.image = image;
this.price = price;
this.storeId = storeId;
}
public Menu() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Number getPrice() {
return price;
}
public void setPrice(Number price) {
this.price = price;
}
public String getStoreId() {
return storeId;
}
public void setStoreId(String storeId) {
this.storeId = storeId;
}
}
Thanks for helping

you need to populate the RecycleChildAdapter.java in the onBindViewHolder of RecycleParentAdapter.java
like:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private CircleImageView storeImage;
private TextView storeName;
public RecyclerView recycler_view_child;
ViewHolder(View itemView) {
super(itemView);
storeImage = itemView.findViewById(R.id.ivListStoreImage);
storeName = itemView.findViewById(R.id.tvListStoreName);
recycler_view_child = view.findViewById(R.id.recyclerchild);
itemView.setOnClickListener(this);
}
and:
public class RecycleParentMenuAdapter extends RecyclerView.Adapter<RecycleParentMenuAdapter.ViewHolder>{
private ArrayList<Store> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
public RecycleChildAdapter adapter;
finally:
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.storeName.setText(mData.get(position).getName());
// holder.storeImage.setImageURI(mData.get(position).getImage());
LinearLayoutManager manager=new LinearLayoutManager(context);
manager.setOrientation(LinearLayoutManager.HORIZONTAL);
holder.recycler_view_child.setLayoutManager(manager);
adapter = new ChildAdapter(yourdatalist, context);
holder.recycler_view_child.setAdapter(adapter);
}

Related

Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference

Idk why is it not working, Im trying to transfer data, i'm doing an app but when i run it i get an error, the Error is in the BlogActivity Class
"showData(getIntent().getExtras().getParcelable(EXTRAS_BLOG));"(java.lang.NullPointerException).
This is BlogActivity Class:
public class BlogActivity extends AppCompatActivity{
private static final String EXTRAS_BLOG = "EXTRAS_BLOG";
private TextView textTitle;
private TextView textDate;
private TextView textAuthor;
private TextView textRating;
private TextView textDescription;
private TextView textViews;
private RatingBar ratingBar;
private ImageView imageAvatar;
private ImageView imageMain;
private ImageView imageBack;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blogpage);
imageMain = findViewById(R.id.yemenImg);
imageAvatar = findViewById(R.id.yemenAvatar);
imageBack = findViewById(R.id.imageBack);
imageBack.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Intent myInt = new Intent(getApplicationContext(),MainActivity.class);
startActivity(myInt);
}
},2);
}
});
textDate = findViewById(R.id.dateYemen);
textTitle = findViewById(R.id.textTitle);
textAuthor = findViewById(R.id.yemenAuthor);
textRating = findViewById(R.id.textRating);
textViews = findViewById(R.id.textViews);
textDescription = findViewById(R.id.textDescription);
ratingBar = findViewById(R.id.ratingBar);
progressBar = findViewById(R.id.progressBar);
showData(getIntent().getExtras().getParcelable(EXTRAS_BLOG));
}
/*private void loadData()
{
BlogHttpClient.INSTANCE.loadBlogArticles(new BlogArticlesCallback() {
#Override
public void onSuccess(final List<Blog> blogList) {
runOnUiThread(new Runnable() {
#Override
public void run() {
showData(blogList.get(0));
}
});
}
#Override
public void onError() {
runOnUiThread(new Runnable() {
#Override
public void run() {
showErrorSnackbar();
}
});
}
});
}*/
private void showData(Blog blog)
{
progressBar.setVisibility(View.GONE);
textTitle.setText(blog.getTitle());
textDate.setText(blog.getDate());
textAuthor.setText(blog.getAuthor().getName());
textRating.setText(String.valueOf(blog.getRating()));
textViews.setText(String.format("(%d views)", blog.getViews()));
textDescription.setText(blog.getDescription());
textDescription.setText(Html.fromHtml(blog.getDescription(),Html.FROM_HTML_MODE_COMPACT));
ratingBar.setRating(blog.getRating());
ratingBar.setVisibility(View.VISIBLE);
imageBack.setImageResource(R.drawable.ic_baseline_arrow_back_24);
Glide.with(this)
.load(blog.getImage())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageMain);
Glide.with(this)
.load(blog.getAuthor().getAvatar())
.transform(new CircleCrop())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageAvatar);
}
/*private void showErrorSnackbar()
{
View rootView = findViewById(android.R.id.content);
Snackbar snackbar = Snackbar.make(rootView,"Error during loading blog articles",
Snackbar.LENGTH_INDEFINITE);
snackbar.setActionTextColor(Color.parseColor("#e0af1f"));
snackbar.setAction("Retry", v -> {
snackbar.dismiss();
});
snackbar.show();
}*/
public static void startBlogDetailsActivity(Activity activity, Blog blog) {
Intent intent = new Intent(activity, BlogActivity.class);
intent.putExtra(EXTRAS_BLOG, blog);
activity.startActivity(intent);
}
Blog Class:
public class Blog implements Parcelable {
private String id;
private Author author;
private String title;
private String date;
private String image;
private String description;
private int views;
private float rating;
protected Blog(Parcel in) {
id = in.readString();
title = in.readString();
date = in.readString();
image = in.readString();
description = in.readString();
views = in.readInt();
rating = in.readFloat();
author = in.readParcelable(Author.class.getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(title);
dest.writeString(date);
dest.writeString(image);
dest.writeString(description);
dest.writeInt(views);
dest.writeFloat(rating);
dest.writeParcelable(author, 0);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Blog> CREATOR = new Creator<Blog>() {
#Override
public Blog createFromParcel(Parcel in) {
return new Blog(in);
}
#Override
public Blog[] newArray(int size) {
return new Blog[size];
}
};
public String getTitle() {
return title;
}
public String getDate() {
return date;
}
public String getImage() {
return image;
}
public String getDescription() {
return description;
}
public int getViews() {
return views;
}
public float getRating() {
return rating;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String getId() {
return id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Blog blog = (Blog) o;
return views == blog.views &&
Float.compare(blog.rating, rating) == 0 &&
Objects.equals(id, blog.id) &&
Objects.equals(author, blog.author) &&
Objects.equals(title, blog.title) &&
Objects.equals(date, blog.date) &&
Objects.equals(image, blog.image) &&
Objects.equals(description, blog.description);
}
#Override
public int hashCode() {
return Objects.hash(id, author, title, date, image, description, views, rating);
}
This is Main Activity Class:
public class MainActivity extends AppCompatActivity {
private MainAdapter adapter;
private SwipeRefreshLayout refreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainAdapter(blog ->
BlogActivity.startBlogDetailsActivity(this, blog));
RecyclerView recyclerView = findViewById(R.id.recylerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
refreshLayout = findViewById(R.id.refresh);
refreshLayout.setOnRefreshListener(this::loadData);
loadData();
}
private void loadData()
{
refreshLayout.setRefreshing(true);
BlogHttpClient.INSTANCE.loadBlogArticles(new BlogArticlesCallback() {
#Override
public void onSuccess(final List<Blog> blogList) {
runOnUiThread(new Runnable() {
#Override
public void run() {
refreshLayout.setRefreshing(false);
adapter.submitList(blogList);
}
});
}
#Override
public void onError() {
runOnUiThread(new Runnable() {
#Override
public void run() {
refreshLayout.setRefreshing(false);
showErrorSnackbar();
}
});
}
});
}
private void showErrorSnackbar() {
View rootView = findViewById(android.R.id.content);
Snackbar snackbar = Snackbar.make(rootView,"Error during loading blog articles",
Snackbar.LENGTH_INDEFINITE);
snackbar.setActionTextColor(Color.parseColor("#e0af1f"));
snackbar.setAction("Retry", v -> {
loadData();
snackbar.dismiss();
});
snackbar.show();
}
This is MainAdapter Class:
public class MainAdapter extends ListAdapter<Blog, MainAdapter.MainViewHolder>{
public interface OnItemClickListener{
void onItemClicked(Blog blog);
}
private OnItemClickListener clickListener;
public MainAdapter(OnItemClickListener clickListener){
super(DIFF_CALLBACK);
this.clickListener = clickListener;
}
#NonNull
#Override
public MainAdapter.MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.activity_listlayout,parent,false);
return new MainViewHolder(view, clickListener);
}
#Override
public void onBindViewHolder(#NonNull MainAdapter.MainViewHolder holder, int position)
{
holder.bindTo(getItem(position));
}
static class MainViewHolder extends RecyclerView.ViewHolder
{
private TextView textTitle;
private TextView textDate;
private ImageView imageAvatar;
private Blog blog;
public MainViewHolder(#NonNull View itemView, OnItemClickListener listener)
{
super(itemView);
itemView.setOnClickListener(view -> listener.onItemClicked(blog));
textTitle = itemView.findViewById(R.id.textTitle);
textDate = itemView.findViewById(R.id.textDate);
imageAvatar = itemView.findViewById(R.id.imageAvatar);
}
void bindTo(Blog blog)
{
textTitle.setText(blog.getTitle());
textDate.setText(blog.getDate());
Glide.with(itemView)
.load(blog.getAuthor().getAvatar())
.transform(new CircleCrop())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageAvatar);
}
}
private static final DiffUtil.ItemCallback<Blog> DIFF_CALLBACK =
new DiffUtil.ItemCallback<Blog>()
{
#Override
public boolean areItemsTheSame(#NonNull Blog oldItem, #NonNull Blog newItem)
{
return oldItem.getId().equals(newItem.getId());
}
#Override
public boolean areContentsTheSame(#NonNull Blog oldItem, #NonNull Blog newItem)
{
return oldItem.equals(newItem);
}
};
You may set value to blog variable in MainViewHolder.
Add this line to your bindTo() method body:
this.blog = blog

How to call my "WebActivty" through RecyclerView URL (am using firbase for data sending)

myadapter.java
'how to open link in my WebActivity.java through the myadapter.java'
public class myadapter extends FirebaseRecyclerAdapter<model,myadapter.myViewHolder> implements View.OnClickListener{
public myadapter(#NonNull FirebaseRecyclerOptions<model> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myViewHolder holder, int position, #NonNull model model) {
holder.name.setText(model.getName());
holder.dcr.setText(model.getDcr());
Glide.with(holder.img.getContext()).load(model.getImgurl()).into(holder.img);
}
#Override
public void onClick(View view) {
Context context = view.getContext();
view.getContext().startActivity(new Intent(view.getContext(),WebActivity.class));
Intent intent = new Intent();
context.startActivity(intent);
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_product,parent,false);
return new myViewHolder(view);
}
class myViewHolder extends RecyclerView.ViewHolder{
ImageView img;
TextView name,dcr;
CardView link;
Context context;
public myViewHolder(#NonNull View itemView) {
super(itemView);
img=(ImageView)itemView.findViewById(R.id.image);
name=(TextView)itemView.findViewById(R.id.title);
dcr=(TextView)itemView.findViewById(R.id.dcrtxt);
link=(CardView) itemView.findViewById(R.id.cardview);
}
}
}
model.java
'this is my model class please help me'
public class model {
String dcr,imgurl,name,link;
model()
{
}
public model(String dcr, String imgurl, String name) {
this.dcr = dcr;
this.imgurl = imgurl;
this.name = name;
this.name = link;
}
public String getDcr() {
return dcr;
}
public void setDcr(String dcr) {
this.dcr = dcr;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.name = link;
}
}
WebActivity.java
'this is simple webactivity for loading urls'
public class WebActivity extends AppCompatActivity {
private WebView webView;
String url = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
webView = findViewById(R.id.myweb);
url = getIntent().getStringExtra("URL_NAME");
webView.loadUrl(url);
}
}

Open an specific activity when I click an item from an recyclerView

I need some help with two of my recycler views(one named "recentRecycler", and the other "topPlacesRecycler").My question is, how do I make to be redirected on a specific Activity when I click a specific item from the recycler. For example:
1- when I click the first item from the "recentRecycler" to be redirected to "Parlament.class"
2- when I click the first item from the "topPlacesRecycler" to be redirected to "Ramada.class"
etc.
My Main Activity which is named "BUCint" (The code from the bottom is from a drawerlayout that I use for my project)
public class BUCint extends AppCompatActivity {
DrawerLayout drawerLayout;
RecyclerView recentRecycler, topPlacesRecycler;
RecentsAdapter recentsAdapter;
TopPlacesAdapter topPlacesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buc_int);
drawerLayout = findViewById(R.id.drawer_layout);
List<RecentsData> recentsDataList = new ArrayList<>();
recentsDataList.add(new RecentsData("Palatul Parlamentului","Cladire administrativă","40 lei",R.drawable.palatulparlamentului));
recentsDataList.add(new RecentsData("Arcul de Triumf","Monument istoric","Gratis",R.drawable.arctriumf));
recentsDataList.add(new RecentsData("Carturesti Carusel","Librarie","Gratis",R.drawable.carturesti));
recentsDataList.add(new RecentsData("Parcul Herăstrău","Parc","Gratis",R.drawable.parculherastrau));
recentsDataList.add(new RecentsData("Parcul Cișmigiu","Parc","Gratis",R.drawable.parculcismigiu));
recentsDataList.add(new RecentsData("Muzeul Antipa","Muzeu","20 lei",R.drawable.muzeulantipa));
setRecentRecycler(recentsDataList);
List<TopPlacesData> topPlacesDataList = new ArrayList<>();
topPlacesDataList.add(new TopPlacesData("Ramada Parc","Sectorul 1","227 lei",R.drawable.ramadaparc));
topPlacesDataList.add(new TopPlacesData("Berthelot","Sectorul 1","207 lei",R.drawable.bethelot));
topPlacesDataList.add(new TopPlacesData("Union Plaza","Centru","215 lei",R.drawable.unionplaza));
topPlacesDataList.add(new TopPlacesData("Rin Grande","Sectorul 4","223 lei",R.drawable.ringrande));
topPlacesDataList.add(new TopPlacesData("Hilton Garden","Centru","240 lei",R.drawable.hiltongarden));
setTopPlacesRecycler(topPlacesDataList);
}
private void setRecentRecycler(List<RecentsData> recentsDataList){
recentRecycler = findViewById(R.id.recent_recycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
recentRecycler.setLayoutManager(layoutManager);
recentsAdapter = new RecentsAdapter(this, recentsDataList);
recentRecycler.setAdapter(recentsAdapter);
}
private void setTopPlacesRecycler(List<TopPlacesData> topPlacesDataList){
topPlacesRecycler = findViewById(R.id.top_places_recycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
topPlacesRecycler.setLayoutManager(layoutManager);
topPlacesAdapter = new TopPlacesAdapter(this, topPlacesDataList);
topPlacesRecycler.setAdapter(topPlacesAdapter);
}
public void ClickMenu(View view){
BUCM.openDrawer(drawerLayout);
}
public void ClickLogo(View view){
BUCM.closeDrawer(drawerLayout);
}
public void ClickHome(View view){
BUCM.redirectActivity(this, Acasa.class);
}
public void ClickLinii(View view){
BUCM.redirectActivity(this,BUClinii.class);
}
public void ClickPreturi(View view){
BUCM.redirectActivity(this, BUCpreturi.class);
}
public void Clickint(View view){
recreate();
}
public void ClickSetari(View view) {
BUCM.redirectActivity(this, Setari.class);
}
public void ClickInformatii(View view){
BUCM.redirectActivity(this, Informatii.class);
}
public void ClickLogout(View view){
BUCM.logout(this);
}
#Override
protected void onPause(){
super.onPause();
BUCM.closeDrawer(drawerLayout);
}
}
The Adapter for recentRecycler, named RecentsAdapter
public class RecentsAdapter extends RecyclerView.Adapter<RecentsAdapter.RecentsViewHolder> {
Context context;
List<RecentsData> recentsDataList;
public RecentsAdapter(Context context, List<RecentsData> recentsDataList) {
this.context = context;
this.recentsDataList = recentsDataList;
}
#NonNull
#Override
public RecentsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recents_row_item, parent, false);
return new RecentsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecentsViewHolder holder, int position) {
holder.countryName.setText(recentsDataList.get(position).getCountryName());
holder.placeName.setText(recentsDataList.get(position).getPlaceName());
holder.price.setText(recentsDataList.get(position).getPrice());
holder.placeImage.setImageResource(recentsDataList.get(position).getImageUrl());
}
#Override
public int getItemCount() {
return recentsDataList.size();
}
public static final class RecentsViewHolder extends RecyclerView.ViewHolder{
ImageView placeImage;
TextView placeName, countryName, price;
public RecentsViewHolder(#NonNull View itemView) {
super(itemView);
placeImage = itemView.findViewById(R.id.place_image);
placeName = itemView.findViewById(R.id.place_name);
countryName = itemView.findViewById(R.id.country_name);
price = itemView.findViewById(R.id.price);
}
}
}
The DataModel for recentRecycler, named RecentsData
package com.example.spinner.model;
public class RecentsData {
String placeName;
String countryName;
String price;
Integer imageUrl;
public Integer getImageUrl() {
return imageUrl;
}
public void setImageUrl(Integer imageUrl) {
this.imageUrl = imageUrl;
}
public RecentsData(String placeName, String countryName, String price, Integer imageUrl) {
this.placeName = placeName;
this.countryName = countryName;
this.price = price;
this.imageUrl = imageUrl;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
The Adapter for topPlacesRecycler, named TopPlacesAdapter
public class TopPlacesAdapter extends RecyclerView.Adapter<TopPlacesAdapter.TopPlacesViewHolder> {
Context context;
List<TopPlacesData> topPlacesDataList;
public TopPlacesAdapter(Context context, List<TopPlacesData> topPlacesDataList) {
this.context = context;
this.topPlacesDataList = topPlacesDataList;
}
#NonNull
#Override
public TopPlacesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.top_places_row_item, parent, false);
return new TopPlacesViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TopPlacesViewHolder holder, int position) {
holder.countryName.setText(topPlacesDataList.get(position).getCountryName());
holder.placeName.setText(topPlacesDataList.get(position).getPlaceName());
holder.price.setText(topPlacesDataList.get(position).getPrice());
holder.placeImage.setImageResource(topPlacesDataList.get(position).getImageUrl());
}
#Override
public int getItemCount() {
return topPlacesDataList.size();
}
public static final class TopPlacesViewHolder extends RecyclerView.ViewHolder{
ImageView placeImage;
TextView placeName, countryName, price;
public TopPlacesViewHolder(#NonNull View itemView) {
super(itemView);
placeImage = itemView.findViewById(R.id.place_image);
placeName = itemView.findViewById(R.id.place_name);
countryName = itemView.findViewById(R.id.country_name);
price = itemView.findViewById(R.id.price);
}
}
}
The DataModel for topPlacesRecycler, named TopPlacesData
public class TopPlacesData {
String placeName;
String countryName;
String price;
Integer imageUrl;
public Integer getImageUrl() {
return imageUrl;
}
public void setImageUrl(Integer imageUrl) {
this.imageUrl = imageUrl;
}
public TopPlacesData(String placeName, String countryName, String price, Integer imageUrl) {
this.placeName = placeName;
this.countryName = countryName;
this.price = price;
this.imageUrl = imageUrl;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
I'm pretty new with Android Studio so every feedback would be gladly accepted.
Thanks in advance!
The best solution that does not overload the adapter would be to use interface.
Declare an interface in your adapter like this...
public class RecentsAdapter extends RecyclerView.Adapter<RecentsAdapter.RecentsViewHolder> {
Context context;
List<RecentsData> recentsDataList;
private RecentsAdapter.OnRecentItemclickListener listener;
public void setOnRecentItemclickListener(RecentsAdapter.OnRecentItemclickListener listener){
this.listener = listener;
}
public RecentsAdapter(Context context, List<RecentsData> recentsDataList) {
this.context = context;
this.recentsDataList = recentsDataList;
}
#NonNull
#Override
public RecentsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recents_row_item, parent, false);
return new RecentsViewHolder(view, listener);
}
#Override
public void onBindViewHolder(#NonNull RecentsViewHolder holder, int position) {
holder.countryName.setText(recentsDataList.get(position).getCountryName());
holder.placeName.setText(recentsDataList.get(position).getPlaceName());
holder.price.setText(recentsDataList.get(position).getPrice());
holder.placeImage.setImageResource(recentsDataList.get(position).getImageUrl());
}
#Override
public int getItemCount() {
return recentsDataList.size();
}
public static final class RecentsViewHolder extends RecyclerView.ViewHolder{
ImageView placeImage;
TextView placeName, countryName, price;
public RecentsViewHolder(#NonNull View itemView, RecentsAdapter.OnRecentItemclickListener listener) {
super(itemView);
placeImage = itemView.findViewById(R.id.place_image);
placeName = itemView.findViewById(R.id.place_name);
countryName = itemView.findViewById(R.id.country_name);
price = itemView.findViewById(R.id.price);
itemView.setOnclickListener( -> {
if(listner == null)return;
int pos = getAdapterposition()
if(pos == RecyclerView.NO_POSITION)return;
listner.onRecentItemclickListener(pos);
});
}
}
public interface OnRecentItemclickListener {
void onRecentItemClickListener(int position);
}
}
Add then in you activity
private void setRecentRecycler(List<RecentsData> recentsDataList){
recentRecycler = findViewById(R.id.recent_recycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
recentRecycler.setLayoutManager(layoutManager);
recentsAdapter = new RecentsAdapter(this, recentsDataList);
recentRecycler.setAdapter(recentsAdapter);
recentsAdapter.setOnRecentItemclickListener(this::onOpenParlamentClass)
}
private void onOpenParlamentClass(int position){
//perform your intent here. you can also get the clicked item using the position of the data list and pass it to the receiving activity
}
Happy coding. If you are new to android you can also consider Kotlin.
public static final class RecentsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView placeImage;
TextView placeName, countryName, price;
public RecentsViewHolder(#NonNull View itemView) {
super(itemView);
placeImage = itemView.findViewById(R.id.place_image);
placeName = itemView.findViewById(R.id.place_name);
countryName = itemView.findViewById(R.id.country_name);
price = itemView.findViewById(R.id.price);
itemView.setOnClickListener(this);
//you can do same code for another recyclerview.
}
#Override
public void onClick(View view) {
Intent intent = new Intent(context, Parlament.class);
view.getContext().startActivity(intent);
}
}

Add to favorite using room Database

I'm referring this tutorial ==> https://uniqueandrocode.com/add-to-favourites-and-display-favourites-in-recyclerview/ in my project I have bottom navigation...I am trying to add favourites in the first tab and displaying favourites in the second tab in the bottom navigation bar. I'm using Room library.
When activity loads favourites are all blank at first, but when I first row as favourite and go-to favourite tab it displays properly but when I came back to the first tab it fills all the favourites icon automatically (which I have not done I had only done the first row)
Really need help. Thanks in advance.
Dao:
#Dao
public interface FavoriteDao {
#Insert
public void addData(FavoriteList favoriteList);
#Query("select * from favoritelist")
public List<FavoriteList> getFavoriteData();
#Query("SELECT EXISTS (SELECT 1 FROM favoritelist WHERE id=:id)")
public int isFavorite(int id);
#Delete
public void delete(FavoriteList favoriteList);
}
Database:
#Database(entities={FavoriteList.class},version = 1)
public abstract class FavoriteDatabase extends RoomDatabase {
public abstract FavoriteDao favoriteDao();
}
FavoriteList:
#Entity(tableName="favoritelist")
public class FavoriteList {
#PrimaryKey
private int id;
#ColumnInfo(name = "source")
private String source;
#ColumnInfo(name = "author")
private String author;
#ColumnInfo(name = "title")
private String title;
#ColumnInfo(name = "description")
private String description;
#ColumnInfo(name = "url")
private String url;
#ColumnInfo(name = "urlToImage")
private String urlToImage;
#ColumnInfo(name = "publishedAt")
private String publishedAt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
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 String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
}
News fragment:
public class news extends Fragment {
ImageView favbtn;
RecyclerView recyclerView;
SwipeRefreshLayout swipeRefreshLayout;
EditText etQuery;
Button btnSearch;
Adapter adapter;
List<Articles> articles = new ArrayList<>();
public static FavoriteDatabase favoriteDatabase;
public news() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_news, container, false);
swipeRefreshLayout = view.findViewById(R.id.swiprefresh);
etQuery = view.findViewById(R.id.etQuery);
btnSearch = view.findViewById(R.id.btnSearch);
favoriteDatabase= Room.databaseBuilder(getActivity(),FavoriteDatabase.class,"myfavdb").
allowMainThreadQueries().build();
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
final String country = getCountry();
retrieveJson("", country, API_Key);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!etQuery.getText().toString().equals("")) {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson(etQuery.getText().toString(), country, API_Key);
}
});
retrieveJson(etQuery.getText().toString(), country, API_Key);
} else {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson("", country, API_Key);
}
});
retrieveJson("", country, API_Key);
}
}
});
return view;
}
private void showChangeLanguageDialog() {
}
public void retrieveJson(String query, String country, String apiKey) {
swipeRefreshLayout.setRefreshing(true);
Call<Headlines> call;
if (!etQuery.getText().toString().equals("")) {
call = ApiClient.getInstance().getApi().getSpecifiedData(query, apiKey);
} else {
call = ApiClient.getInstance().getApi().getHeadLines(country, apiKey);
}
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if (response.isSuccessful() && response.body().getArticles() != null) {
swipeRefreshLayout.setRefreshing(false);
// articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(getContext(), articles);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry() {
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final Adapter.ViewHolder holder, final int position) {
final Articles a = articles.get(position);
String imageUrl = a.getUrlToImage();
String url = a.getUrl();
holder.tvTitle.setText(a.getTitle());
Picasso.get().load(imageUrl).into(holder.imageView);
holder.tvSource.setText(a.getSource().getName());
holder.tvDate.setText(dateTime(a.getPublishedAt()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailedActivity.class);
intent.putExtra("title",a.getTitle());
intent.putExtra("source",a.getSource().getName());
intent.putExtra("time",dateTime(a.getPublishedAt()));
intent.putExtra("desc",a.getDescription());
intent.putExtra("imageUrl",a.getUrlToImage());
intent.putExtra("url",a.getUrl());
context.startActivity(intent);
}
});
if (news.favoriteDatabase.favoriteDao().isFavorite(articles.get(position).getId())==1)
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
else
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
holder.bookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FavoriteList favoriteList = new FavoriteList();
int id = articles.get(position).getId();
String source = articles.get(position).getSource().getName();
String author = articles.get(position).getAuthor();
String publishedAt = articles.get(position).getPublishedAt();
String description = articles.get(position).getDescription();
String title = articles.get(position).getTitle();
String url = articles.get(position).getUrl();
String urlToImage = articles.get(position).getUrlToImage();
favoriteList.setId(id);
favoriteList.setAuthor(author);
favoriteList.setDescription(description);
favoriteList.setSource(source);
favoriteList.setPublishedAt(publishedAt);
favoriteList.setTitle(title);
favoriteList.setUrl(url);
favoriteList.setUrlToImage(urlToImage);
favoriteList.setPublishedAt(dateTime(articles.get(position).getPublishedAt()));
if (news.favoriteDatabase.favoriteDao().isFavorite(id)!=1){
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
news.favoriteDatabase.favoriteDao().addData(favoriteList);
}else {
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
news.favoriteDatabase.favoriteDao().delete(favoriteList);
}
}
});
}
#Override
public int getItemCount() {
return articles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle, tvSource, tvDate;
ImageView imageView;
ImageButton bookmark;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvId);
tvSource = itemView.findViewById(R.id.tvSource);
tvDate = itemView.findViewById(R.id.tvDate);
imageView = itemView.findViewById(R.id.image);
cardView = itemView.findViewById(R.id.cardView);
bookmark = itemView.findViewById(R.id.favrr);
}
}
Steps to debug:
Add 2-3 items as Favs.
Restart the Application.
Check if it shows those items as fav after restarting application .
also add logs to those if conditions where you are changing the drawables.
After looking at your JSON it looks like id is what creating problems. Id is null for all your json items so when fav. one it shows fav. to all.
Solution : Use another field to check if the data is added to fav.list
Delete will not work either
Try
#Query("DELETE FROM favoritelist WHERE title = :title")
void deleteByUserId(String title);
To delete item
Also https://github.com/amitshekhariitbhu/Android-Debug-Database
check this library to debug your database

I want to display an image from drawable and combine it with data from json-api into recylerview

I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}

Categories

Resources