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);
}
}
Related
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
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);
}
}
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);
}
My RecyclerView not show any data from Firebase. I don't see any errors at logcat so I don't know why. I followed guide from youtube video. But still nothing. I'm using android 8.0 and API 27. Hope Somebody can help.
My Main Activity Code:
public class ViewProduct extends AppCompatActivity {
DatabaseReference ref;
ArrayList<Model> list;
private RecyclerView recyclerView;
private RecyclerView.Adapter viewHolder;
private RecyclerView.LayoutManager layoutManager;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_product) ;
ref = FirebaseDatabase.getInstance().getReference().child("buddymealplanneruser").
child("Products");
recyclerView = findViewById(R.id.stallproductRecyclerView);
//recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//SEARCH VIEW
searchView = findViewById(R.id.searchProductStall);
//ADAPTER
list = new ArrayList<>();
viewHolder = new ViewHolder(list);
recyclerView.setAdapter(viewHolder);
}
#Override
protected void onRestart() {
super.onRestart();
if (ref!=null)
{
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
//list = new ArrayList<>();
list.clear();
for(DataSnapshot ds : dataSnapshot.getChildren())
{
list.add(ds.getValue(Model.class));
}
//ViewHolder viewHolder = new ViewHolder(list);
//recyclerView.setAdapter(viewHolder);
viewHolder.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ViewProduct.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
if (searchView !=null)
{
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s)
{
return false;
}
#Override
public boolean onQueryTextChange(String s) {
search(s);
return true;
}
});
}
}
private void search(String str) {
ArrayList<Model> myList = new ArrayList<>();
for(Model object : list)
{
if(object.getProductName().toLowerCase().contains(str.toLowerCase()))
{
myList.add(object);
}
}
ViewHolder viewHolder = new ViewHolder(myList);
recyclerView.setAdapter(viewHolder);
}
}
My Adapter:
public class ViewHolder extends RecyclerView.Adapter<ViewHolder.MyViewHolder> {
ArrayList<Model> list;
public ViewHolder (ArrayList<Model> list)
{
this.list=list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_product, viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.productName.setText(list.get(i).getProductName());
myViewHolder.productCalorie.setText(list.get(i).getProductCalorie());
myViewHolder.StallId.setText(list.get(i).getStallId());
myViewHolder.productType.setText(list.get(i).getProductType());
myViewHolder.productServing.setText(list.get(i).getProductServing());
myViewHolder.statusProduct.setText(list.get(i).getStatusProduct());
}
#Override
public int getItemCount()
{
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView productName, productCalorie, StallId;
TextView productType, productServing, statusProduct;
ImageView productImageView;
public MyViewHolder (#NonNull View itemView){
super((itemView));
productName = itemView.findViewById(R.id.productTitle);
productCalorie = itemView.findViewById(R.id.productDescriptionCalorie);
StallId = itemView.findViewById(R.id.productDescriptionStallId);
productType = itemView.findViewById(R.id.productDescriptionType);
productServing=itemView.findViewById(R.id.productDescriptionServing);
statusProduct=itemView.findViewById(R.id.productDescriptionAvailibility);
//productImageView = itemView.findViewById(R.id.productImageView);
}
}
}
My Model :
package com.example.buddymealplannerstall.Child;
import android.view.Display;
public class Model {
//String productName, productImage, productCalorie, StallId, productType, productServing, statusProduct;
private String StallId;
private String productCalorie;
private String productImage;
private String productName;
private String productServing;
private String productType;
private String statusProduct;
public Model (String StallId,
String productCalorie,
String productImage,
String productName,
String productServing,
String productType,
String statusProduct){
this.StallId = StallId;
this.productCalorie = productCalorie;
this.productImage = productImage;
this.productName = productName;
this.productServing = productServing;
this.productType = productType;
this.statusProduct = statusProduct;
}
public Model(){
}
public String getStallId() {
return StallId;
}
public void setStallId(String stallId) {
StallId = stallId;
}
public String getProductCalorie() {
return productCalorie;
}
public void setProductCalorie(String productCalorie) {
this.productCalorie = productCalorie;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductServing() {
return productServing;
}
public void setProductServing(String productServing) {
this.productServing = productServing;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getStatusProduct() {
return statusProduct;
}
public void setStatusProduct(String statusProduct) {
this.statusProduct = statusProduct;
}
}
Screen Shot of my firebase and my apps.
firebase
my app
According to your comment:
yes, buddymealplanner is my project's name
Please note that there is no need to add the name of your project as a child in the reference. So please change the following line of code:
ref = FirebaseDatabase.getInstance().getReference().child("buddymealplanneruser").
child("Products");
Simply to:
ref = FirebaseDatabase.getInstance().getReference().child("Products");
I dont think you are populating your list, you are sending it empty. From what I can see, you only add items to the list when you are restarting the activity. Try either populating it before sendinig the list, or changing the onRestart() for an onStart() or an onResume().
I can't understand why it makes problem with it. It take data from server with retrofit and it can't use that data in recyclerview. It make problem with Constructor but I can not understand why it makes problem with it. That can get data from service successfully with this Model, but problem is to put adapter and recyclierview. How can solve it?
ProductPage.java
public class ProductPage {
private int productID;
private String productName;
private String productDescription;
private List<String> productImages;
private List<ProductPrice> productPrices;
public int getProductID() {
return productID;
}
public void setProductID(int productID) {
this.productID = productID;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public List<String> getProductImages() {
return productImages;
}
public void setProductImages(List<String> productImages) {
this.productImages = productImages;
}
public List<ProductPrice> getProductPrices() {
return productPrices;
}
public void setProductPrices(List<ProductPrice> productPrices) {
this.productPrices = productPrices;
}
}
ProductDetailAdapter.java
public class ProductDetailAdapter extends RecyclerView.Adapter<ProductDetailAdapter.ViewHolder> {
private Context mContext;
int rawLayout;
private List<ProductPage> productPageList;
private int cartAmount;
public ProductDetailAdapter(Context mContext,int rawLayout, List<ProductPage> productPageList, CartListener cartListener) {
this.mContext = mContext;
this.rawLayout = rawLayout;
this.productPageList = productPageList;
this.cartListener = cartListener;
}
#NonNull
#Override
public ProductDetailAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View mView = LayoutInflater.from(parent.getContext()).inflate(rawLayout, parent, false);
return new ViewHolder(mView); }
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
Glide.with(mContext).load(productPageList.get(position).getProductPrices().get(position).getShopImage())
.apply(RequestOptions.placeholderOf(R.drawable.ic_glide_img).error(R.drawable.ic_glide_warning)).
into(viewHolder.imgProductDetail);
viewHolder.textProductDetailCost.setText(Double.toString(productPageList
.get(position).getProductPrices().get(position).getShopProductPrice())+" TL");
viewHolder.textProductDetailMarket.setText(productPageList.get(position).getProductPrices().get(position).getShopName());
}
#Override
public int getItemCount() {
return productPageList.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private ImageView imgProductDetail;
private TextView textProductDetailCost, textProductDetailMarket;
private Button btnProductDetail;
private CardView cardViewProductDetail;
ViewHolder(View itemView){
super(itemView);
imgProductDetail = itemView.findViewById(R.id.imageView_product_detail);
textProductDetailCost = itemView.findViewById(R.id.text_product_detail_cost);
textProductDetailMarket = itemView.findViewById(R.id.textViewProductShopName);
btnProductDetail = itemView.findViewById(R.id.buttonProductDetail);
cardViewProductDetail = itemView.findViewById(R.id.cardViewProductDetail);
}
}
public interface CartListener {
void onProductSelect(ProductPage productPage);
}
}
ProductActivity.java
public class ProductActivity extends AppCompatActivity implements ProductDetailAdapter.CartListener {
TextView textProductName, textDescription;
RecyclerView recyclerViewProduct;
protected RecyclerView.LayoutManager mLayoutManager;
String productCost, productMarket, productImage, productTitle, prdouctMarketImage;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
init();
loadProductPage();
}
private void init() {
textProductName = findViewById(R.id.text_product_title);
imgProduct = findViewById(R.id.img_product);
recyclerViewProduct = findViewById(R.id.product_recycylerwiew);
textDescription = findViewById(R.id.text_product_description);
textDescription.setMovementMethod(new ScrollingMovementMethod()); // Scroll yapabilmek için açmıştım
mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewProduct.setLayoutManager(mLayoutManager);
private void loadProductPage() {
ApiInterface apiInterface = ApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<ProductPage> call = apiInterface.getProductPage(id);
call.enqueue(new Callback<ProductPage>() {
#Override
public void onResponse(Call<ProductPage> call, Response<ProductPage> response) {
if (response.isSuccessful()) {
ProductPage product_page_list = response.body();
textProductName.setText(product_page_list.getProductName());
textDescription.setText(product_page_list.getProductDescription());
Glide.with(getApplicationContext()).load(product_page_list.getProductImages())
.apply(RequestOptions.placeholderOf(R.drawable.ic_glide_img).error(R.drawable.ic_glide_warning)).
into(imgProduct);
ProductDetailAdapter myAdapter = new ProductDetailAdapter(getApplicationContext(),R.layout.product_detail_item_view,product_page_list,ProductActivity.this);
recyclerViewProduct.setAdapter(myAdapter);
}
else
ApiErrorUtils.parseError(response);
}
#Override
public void onFailure(Call<ProductPage> call, Throwable t) {
Log.d("response","apiError");
}
});
}
#Override
public void onProductSelect(ProductPage productPage) {
}
You are just passing ProductPage object to adapter.
ProductPage product_page_list = response.body();
but your adapter required
List<ProductPage> productPageList
So you need to add product object to product list like this
ProductPage productPage = response.body();
List<ProductPage> productList=new ArrayList<>();
productList.add(productPage);
ProductPage product_page_list = response.body();
product_page_list is not List<ProductPage>()
in your adapter need List<ProductPage> productPageList