I was using firebaseUI library to populate recycler view using firestore database.
when I try to retrieve the document id when i click on recycler view item it was like this
DocumentSnapshot snapshot = getSnapshots()
.getSnapshot(holder.getAdapterPosition());
final String countryName = snapshot.getId();
I tred this code but getSnapshots() appears by the red colored word and nt workng inside onbindeviewolder so I tried this but not working too
DocumentReference aa=firebaseFirestore.collection("MainCategories").document(String.valueOf(SS));
String aaa=aa.getId();
So is there any method to retrieve the document id because the code above is not working here
private class CategoriesAdapter extends RecyclerView.Adapter<AllCategoriesViewHolder> {
private List<mainCategroies> categorylist;
CategoriesAdapter(List<mainCategroies> categorylist) {
this.categorylist = categorylist;
}
#NonNull
#Override
public AllCategoriesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_maincategory, parent, false);
return new AllCategoriesViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final AllCategoriesViewHolder holder, int position) {
final String categoryName = categorylist.get(position).getCategory_Name();
holder.setCategory_Name(categoryName);
String d = categorylist.get(position).getImageUrl();
holder.setImageUrl(d);
MainActivityProgress.setVisibility(View.GONE);
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public int getItemCount() {
return categorylist.size();
}
}
the holder class
private class AllCategoriesViewHolder extends RecyclerView.ViewHolder {
private View view;
public AllCategoriesViewHolder(final View itemView) {
super(itemView);
view = itemView;
}
void setCategory_Name(String category_Name) {
TextView names = view.findViewById(R.id.CategoryName);
names.setText(category_Name);
}
void setImageUrl(String imageUrl) {
ImageView imageView = view.findViewById(R.id.MainCat_CardViewImage);
Picasso.get()
.load(imageUrl)
.fit()
.into(imageView);
}
}
and the model class
public class CountryItem {
private String CountryName;
public CountryItem(){
}
public CountryItem(String countryName) {
CountryName = countryName;
}
public String getCountryName() {
return CountryName;
}
public void setCountryName(String countryName) {
CountryName = countryName;
}
}
The method you are trying to get uid of item i.e:
DocumentSnapshot snapshot = getSnapshots().getSnapshot(holder.getAdapterPosition());
final String countryName = snapshot.getId();
will work only in case of FirestoreRecyclerAdapter. As you are using a RecyclerView.Adapter you have to add uid in your Model class and then Retrieve it.
CountryItem.class
public class CountryItem {
private String CountryName;
private String uid;
//add getters and setters
}
And while Retrieving the data from firestore add uid field to your object. I assume you are using query for this then it would be like:-
Query query = firestore.collection("Collection").orderBy("CountryName",Query.Direction.ASCENDING);
query.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
for(DocumentSnapshot documentSnapshot: documentSnapshots) {
CountryItem countryItem = documentSnapshot.toObject(CountryItem.class);
countryItem.setuid(documentSnapshot.getId().toString());
countryItemList.add(countryItem);
}
}
});
And onClick of an item you can get uid and pass to your method:-
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uid = categorylist.get(position).getUid();
}
});
Related
HISTOROBJECT.CLASS
public class HistoryObject{
private String mName;
private String mImageUrl;
public HistoryObject(){
}
public HistoryObject(String Name, String Image) {
this.user = Name;
this.msg = Image;
}
private String user, msg;
public String getMsg() {
return msg;
}
public void setMsg(String Name) {
this.msg = Name;
}
public String getUser() {
return user;
}
public void setUser(String Image) {
this.user = Image;
}
}
HISTORYADAPTER.CLASS
public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.ImageViewHolder> {
private Context mContext;
private List<HistoryObject> mUploads;
public HistoryAdapter (Context cx, List<HistoryObject> uploads){
mContext = cx;
mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.listofitems, parent, false);
return new ImageViewHolder(v); }
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
HistoryObject historyObject = mUploads.get(position);
holder.textView.setText(historyObject.getUser());
Picasso.get().load(historyObject.getMsg())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.spapic);
}
#Override
public int getItemCount() {
return mUploads.size() ;
}
public class ImageViewHolder extends RecyclerView.ViewHolder{
public TextView textView;
public ImageView spapic;
public ImageViewHolder(View itemView) {
super(itemView);
textView =(TextView)itemView.findViewById(R.id.nameofspa);
spapic =(ImageView) itemView.findViewById(R.id.spapic);
}
}
}
HOMEPAGE.CLASS
mDatabaseRef = FirebaseDatabase.getInstance().getReference("BeautyCenters");
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
// Log.d("SPAA", "VALUE IS " +dataSnapshot) ;
Log.d("SPAA", "postsnap IS " +postSnapshot) ;
HistoryObject upload = postSnapshot.getValue(HistoryObject.class);
mUploads.add(upload);
}
mHistoryAdapter = new HistoryAdapter(HomePage.this, mUploads);
mHistoryRecyclerView.setAdapter(mHistoryAdapter);
mHistoryAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Iam able to retrieve data and can see all list in logcat but it is not displaying in recyclerview. I also want to retrieve the images from the firebase. iam able to show the adapter but the text is not showing in that adapter instead it is blank and also the picture
I have faced this problem before.
Try moving:
mHistoryRecyclerView.setAdapter(mHistoryAdapter);
mHistoryAdapter.notifyDataSetChanged();
out of the listener class to the bottom of onCreate.
If that doesn't work make sure you have this code added:
#Override
public void onStart() {
super.onStart();
if (mAdapter != null) {
mAdapter.startListening();
}
}
If it is still not working then provide a link of your project and I will play around with it.
I am making an android app where I am using MongoDB and NodeJs as a backend service.I have some posts saved on MongoDb and I am retrieving them in recycler view.I have a button in recycler view when it is clicked I want to fetch an Object Id of an item.
I am successfully fetching all documents in recycler view but the problem is
when I clicked on button in particular item.They are showing Object Id of a document which is inserted recently and not showing correct Object Id of an item.
This is what I have done so far:
MyPostBookAdapter.java
public class MyPostedBookAdapter extends RecyclerView.Adapter<MyPostedBookAdapter.ViewHolder> {
List<PostedModel> listItem;
Activity context;
String id;
public MyPostedBookAdapter(List<PostedModel> listItem, Activity context){
this.listItem = listItem;
this.context = context;
}
#NonNull
#Override
public MyPostedBookAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.posted_book,viewGroup,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final MyPostedBookAdapter.ViewHolder viewHolder, final int i) {
final PostedModel model = listItem.get(i);
//Object Id of post
id = model.getPostId();
viewHolder.userBookName.setText(model.getPurchaseBookName());
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.openbook);
Glide.with(context).load(model.getPurchaseImage()).apply(requestOptions).into(viewHolder.userPostBook);
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,id,Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listItem.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView userPostBook;
TextView userBookName;
Button delete;
public ViewHolder(#NonNull View itemView) {
super(itemView);
userPostBook = (itemView).findViewById(R.id.userPostBook);
userBookName = (itemView).findViewById(R.id.userBookName);
delete = (itemView).findViewById(R.id.delete);
}
}
}
PostedModel.java
public class PostedModel {
String purchaseImage,purchaseBookName,postId;
public PostedModel(){
}
public PostedModel(String purchaseImage, String purchaseBookName,String postId){
this.purchaseBookName = purchaseBookName;
this.purchaseImage = purchaseImage;
this.postId = postId;
}
public String getPurchaseImage() {
return purchaseImage;
}
public void setPurchaseImage(String purchaseImage) {
this.purchaseImage = purchaseImage;
}
public String getPurchaseBookName() {
return purchaseBookName;
}
public void setPurchaseBookName(String purchaseBookName) {
this.purchaseBookName = purchaseBookName;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
}
Please let me know how can I get ObjectId correspond to right item.
Any help would be appreciated.
THANKS
The Issue is,
Recycler view load every object given one by one, so variable id had the value of last object. So you need to take id from the selected view.
The Fix is,
#Override
public void onBindViewHolder(#NonNull final MyPostedBookAdapter.ViewHolder viewHolder, final int i) {
final PostedModel model = listItem.get(i);
//Object Id of post
id = model.getPostId();
// You need to set this id to viewHolder.
viewHolder.userBookName.setId(id);
viewHolder.userBookName.setText(model.getPurchaseBookName());
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.openbook);
Glide.with(context).load(model.getPurchaseImage()).apply(requestOptions).into(viewHolder.userPostBook);
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Here you can extract the id which we set at binding
int idOfView = v.userBookName.getId();
Toast.makeText(context,idOfView,Toast.LENGTH_SHORT).show();
}
});
}
Hope this will help you.
Hi i'm stuck on this part where i have 2 collections first one is users and second one is friends. I want my recyclerview to display my friends on the list with the help of current user because on currentUser other peoples id are stored and i want it to display it on the recyclerview but when it displays it i want to get their information from users where they have their username and email stored.
I want only friends collection ids to display on recyclerview with the help of current user id. Then i want to get values from users collection like their name and email value.
Friends collection
users collection
ADAPTER
public class FriendsAdapter extends FirestoreRecyclerAdapter {
private OnItemClicklistener onItemClicklistener;
public FriendsAdapter(#NonNull FirestoreRecyclerOptions<AllUsers> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull FriendsHolder holder, int position, #NonNull AllUsers model) {
holder.textViewUsername.setText(String.valueOf(model.getName()));
holder.textViewEmail.setText(model.getEmail());
holder.setAvatar(model.getAvatar());
}
#NonNull
#Override
public FriendsHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.all_user_list_display, viewGroup, false);
return new FriendsAdapter.FriendsHolder(view);
}
class FriendsHolder extends RecyclerView.ViewHolder {
TextView textViewUsername;
TextView textViewEmail;
ImageView imageViewAvatar;
public FriendsHolder(#NonNull View itemView) {
super(itemView);
textViewUsername = itemView.findViewById(R.id.all_user_username);
textViewEmail = itemView.findViewById(R.id.all_user_userEmail);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && onItemClicklistener != null) {
onItemClicklistener.onItemClick(getSnapshots().getSnapshot(position), position);
}
}
});
}
public void setAvatar(String avatar) {
imageViewAvatar = (ImageView) itemView.findViewById(R.id.all_user_profile_image);
Picasso.get().load(avatar).into(imageViewAvatar);
}
}
public interface OnItemClicklistener {
void onItemClick(DocumentSnapshot snapshot, int position);
}
public void setOnItemClickListener(FriendsAdapter.OnItemClicklistener listener) {
onItemClicklistener = listener;
}
FriendListFragment
public class FriendsListFragment extends Fragment {
private FirebaseFirestore db;
private CollectionReference usersCollection;
private CollectionReference friendsCollection;
private DocumentReference friends;
private DocumentReference users;
private FirebaseUser current_user;
private FriendsAdapter adapter;
public SearchView search_friends;
public FriendsListFragment() {
// 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_friends, container, false);
current_user = FirebaseAuth.getInstance().getCurrentUser();
//FIREBASE
db = FirebaseFirestore.getInstance();
usersCollection = db.collection("users");
friendsCollection = db.collection("friends");
friends = friendsCollection.document(current_user.getUid());
Query friendQuery = usersCollection;
FirestoreRecyclerOptions<AllUsers> options = new FirestoreRecyclerOptions.Builder<AllUsers>()
.setQuery(friendQuery, AllUsers.class)
.build();
adapter = new FriendsAdapter(options);
RecyclerView recyclerView = view.findViewById(R.id.friendsList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return view;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
AllUsersClass
public class AllUsers {
public String name;
public String avatar;
public String email;
public String userId;
public AllUsers() {
}
public AllUsers(String name, String email, String avatar, String userId) {
this.name = name;
this.email = email;
this.avatar = avatar;
this.userId = userId;
}
public String getName() {
return name;
}
public String getAvatar() {
return avatar;
}
public String getEmail() {
return email;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
I'm trying to filter my user from a list of users in the recycler view. But I need to get the uid for each user inside the onBindViewHolder and I don't know how. I'd also like to move the code in onBindViewHolder to the bind method of the ViewHolder but I don't know how to get the context.
Here is what I've done
private void setRecyclerView() {
mUsersRecyclerView.setHasFixedSize(true);
mUsersRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new UserAdapter();
mUsersRecyclerView.setAdapter(mAdapter);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> list = dataSnapshot.getChildren();
// Filter current user
//List<User> userList = new ArrayList<>();
for (DataSnapshot user : list) {
if (!user.getKey().equals(mCurrentUid)) {
mUserList.add(user.getValue(User.class));
}
}
// Setting data
// mAdapter.setItems(userList);
}
#Override public void onCancelled(#NonNull DatabaseError databaseError) {}
});
}
private class UserAdapter extends RecyclerView.Adapter<UserViewHolder> {
#NonNull
#Override
public UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new UserViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.user_item_layout, parent, false));
}
#Override
public void onBindViewHolder(#NonNull UserViewHolder holder, int position) {
User user = mUserList.get(position);
holder.bind(user);
// TODO: move this to holder.bind() method
holder.setThumb_image(user.getThumb_image(),getApplicationContext());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent9 = new Intent(UsersActivity.this,ProfileActivity.class);
intent9.putExtra("user_id", uid); // TODO: get uid for each user here
startActivity(intent9);
}
});
}
#Override
public int getItemCount() {
return mUserList.size();
}
}
private class UserViewHolder extends RecyclerView.ViewHolder {
View mView;
public UserViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void bind(User user) {
TextView nameView = mView.findViewById(R.id.item_name);
nameView.setText(user.getName());
TextView statusView = mView.findViewById(R.id.item_status);
statusView.setText(user.getStatus());
}
public void setThumb_image(String thumb_image, Context ctx) {
CircleImageView imageView = mView.findViewById(R.id.item_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.mipmap.icon).into(imageView);
}
}
Here is a working code with FirebaseRecyclerAdapter that doesn't filter the user.
Add firbaseId in your model while you store data to firebase database
Here's example user model class which stores user's information to firebase
public class User {
private String name;
private String address;
private String firebaseId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getFirebaseId() {
return firebaseId;
}
public void setFirebaseId(String firebaseId) {
this.firebaseId = firebaseId;
}
}
And then store value like below
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference(DATABASE_NAME);
String fireBaseId = databaseReference.push().getKey();
if (fireBaseId != null) {
User user = new User();
user.setName("SSB");
user.setAddress("Some address");
user.setFirebaseId(fireBaseId);
databaseReference.child(fireBaseId).setValue(user);
}
Then you can get id from user model class
I want to add onClickListener to items in the recyclerview showing data from firestore. OnClick should pass the corresponding document id through intent . Pleas help
ProductFragment showing the data
public class ProductFragment extends Fragment {
private static final String TAG = "ProductFragment";
private FirebaseFirestore firestoreDB;
private RecyclerView productRecyclerView;
public ProductFragment() {
// 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_product, container, false);
firestoreDB = FirebaseFirestore.getInstance();
productRecyclerView = (RecyclerView) view.findViewById(R.id.Product_RecyclerView);
LinearLayoutManager recyclerLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
productRecyclerView.setLayoutManager(recyclerLayoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(productRecyclerView.getContext(),
recyclerLayoutManager.getOrientation());
productRecyclerView.addItemDecoration(dividerItemDecoration);
getDocumentsFromCollection();
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
public void getDocumentsFromCollection() {
firestoreDB.collection("products").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
//List<Event> eventList = new ArrayList<>();
List<DocumentSnapshot> documents = task.getResult().getDocuments();
ProductAdapter recyclerViewAdapter = new ProductAdapter(documents, getActivity(), firestoreDB);
recyclerViewAdapter.setOnItemClickListener(new ProductAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.d(TAG, "onItemClick position: " + position);
// Go to the details page for the selected product
}
});
productRecyclerView.setAdapter(recyclerViewAdapter);
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
firestoreDB.collection("products")
.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
}
});
}
}
Adapter
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder>{
public static ClickListener clickListener;
public List<DocumentSnapshot> documents;
private Context context;
private FirebaseFirestore firestoreDB;
public ProductAdapter(List<DocumentSnapshot> list, Context ctx, FirebaseFirestore firestore) {
documents = list;
context = ctx;
firestoreDB = firestore;
}
#Override
public int getItemCount() {
return documents.size();
}
#Override
public ProductAdapter.ViewHolder
onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_layout, parent, false);
ProductAdapter.ViewHolder viewHolder =
new ProductAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ProductAdapter.ViewHolder holder, int position) {
final int itemPos = position;
final DocumentSnapshot snapshot = documents.get(position);
holder.item_name.setText(snapshot.getString("Product"));
holder.price.setText("Rs " + snapshot.getString("Cost") + "/" + snapshot.getString("Per"));
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView item_name;
public TextView price;
public ViewHolder(View view) {
super(view);
itemView.setOnClickListener(this);
item_name = view.findViewById(R.id.List_maintext);
price = view.findViewById(R.id.List_subtext);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(ClickListener clickListener) {
ProductAdapter.clickListener = clickListener;
}
public interface ClickListener {
void onItemClick(int position, View v);
}
}
I tried some methods but all of them crashed.
I need to show a detailed view of the item clicked
You can something like this: Create POJO class and get data from this class.
POJO.class
public class Info {
String product;
String cost;
String per;
#Exclude
private String key;
public Info(){
}
public Info(String product, String cost, String per){
this.product = product;
this.cost = cost;
this.per = per;
}
public <T extends Info> T withId(#NonNull final String id) {
this.key = id;
return (T) this;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
public String getPer() {
return per;
}
public void setPer(String per) {
this.per = per;
}
}
Your fragment, your method
List<Info> documents = new ArrayList<>(); //before onCreate method
public void getDocumentsFromCollection() {
firestoreDB.collection("products").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot snap : task.getResult()){
Info model =snap.toObject(Info.class).withID(snap.getID());
documents.add(model);
ProductAdapter recyclerViewAdapter = new ProductAdapter(documents, getActivity(), firestoreDB);
recyclerViewAdapter.setOnItemClickListener(new ProductAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.d(TAG, "onItemClick position: " + position);
// Go to the details page for the selected product
}
});
productRecyclerView.setAdapter(recyclerViewAdapter);
productRecyclerView.notifyDataSetChanged();
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
firestoreDB.collection("products")
.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
}
});
}
Adapter your:
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder>{
public static ClickListener clickListener;
public List<Info> documents;
private Activity context;
private FirebaseFirestore firestoreDB;
public ProductAdapter(List<Info> list, Activitx ctx, FirebaseFirestore firestore) {
documents = list;
context = ctx;
firestoreDB = firestore;
}
#Override
public int getItemCount() {
return documents.size();
}
#Override
public ProductAdapter.ViewHolder
onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_layout, parent, false);
ProductAdapter.ViewHolder viewHolder =
new ProductAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ProductAdapter.ViewHolder holder, int position) {
final int itemPos = position;
final Info model = documents.get(position);
holder.item_name.setText(model.getProduct());
holder.price.setText("Rs " + model.getCost() + "/" + model.getPer());
holder.itemView.setOnClicListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openNewActivity = new Intent(context, YourNewActivity.class);
openNewActivity.putExtra("id", model.getId());
openNewActivity.putExtra("product", model.getProduct());
context.startActivity(openNewActivity);
}
});
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView item_name;
public TextView price;
public ViewHolder(View view) {
super(view);
itemView.setOnClickListener(this);
item_name = view.findViewById(R.id.List_maintext);
price = view.findViewById(R.id.List_subtext);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(ClickListener clickListener) {
ProductAdapter.clickListener = clickListener;
}
public interface ClickListener {
void onItemClick(int position, View v);
}
}
You can try something like this, I think this can help you to solve your problem.
P.S. Sorry for my english.