Get user uid in recyclerview adapter - android

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

Related

How can i pass user id from my adapter to activity

i am trying to pass holders user.getID to my attendance activity how can i pass users id from my adapter to attendance activity
this is my attendance activity
reference = FirebaseDatabase.getInstance().getReference("parent");
intent = getIntent();
final String currentSubject = intent.getStringExtra("currentSubject");
reference.addValueEventListener(new ValueEventListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
final User user = snapshot.getValue(User.class);
ZoneId zonedId = ZoneId.of("America/Montreal");
final LocalDate today = LocalDate.now(zonedId);
reference = FirebaseDatabase.getInstance().getReference("attendance").child(user.getSchoolcode()).child(grade.getText().toString() + " " + section.getText().toString()).child(currentSubject).child(today.toString()).child(userID);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("attendance", "yes");
reference.updateChildren(hashMap);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
i want to pass it from adapter to this
this is my adapter
public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ViewHolder> {
private Context context;
private List<User> users;
public StudentAdapter(Context context, List<User> users) {
this.context = context;
this.users = users;
}
DatabaseReference reference;
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.student_item, parent, false);
return new StudentAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final User user = users.get(position);
holder.studentName.setText(user.getStudentname() + " " + user.getLastname());
}
#Override
public int getItemCount() {
return users.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView studentName;
public Switch aSwitch;
public ViewHolder(View itemView) {
super(itemView);
studentName = itemView.findViewById(R.id.studentName);
aSwitch = itemView.findViewById(R.id.attendanceSwitch);
}
}
this is my adapter which holds the recyclerview,i am trying to get id of users viewed on attendance activities recyclerview
A way that you can use is callback :
In your adapter define an interface like this :
public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ViewHolder> {
private SendCallBack mCallback;
interface SendCallBack {
void send(int id);
}
//Initial callback in constructor
public StudentAdapter(Context context, List<User> users,SendCallBack callback) {
this.context = context;
this.users = users;
mCallback = callback;
}
//Now in where that you want to pass data use this
mCallback.send(user.getID);
}
Now in your activity implement the callback like this :
public class YourActivty implements YourAdapter.SendCallback {
#Override
public void send(int id) {
}
//For pass callBack for your adapter constructor use this
}
For other ways you can use this link.

How to get data from a firebase table by using another table

So I'm trying get my orders listed as users first and then later when clicked taken to the place where all items can be seen. I have set the order ID as the user uid and now I'm trying to get the uid and from that fetch user data. The mykey i have defined as public in starting but I think I'm using it inside loop and hence can't access it outside. Please help
Code I'm trying
firebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Order");
firebaseDatabase.keepSynced(true);
firebaseDatabase2 = FirebaseDatabase.getInstance().getReference().child("Users");
firebaseDatabase.keepSynced(true);
firebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mykey = snapshot.getKey();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>().setQuery(firebaseDatabase2.child(mykey), Users.class).build();
FirebaseRecyclerAdapter<Users, Orders.UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, Orders.UsersViewHolder>(options)
{
#Override
public Orders.UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_layout,parent,false);
return new Orders.UsersViewHolder(view);
}
#Override
protected void onBindViewHolder(Orders.UsersViewHolder holder, int position, Users model) {
holder.setName(model.getName());
holder.setStatus(model.getMobile());
}
};
mylist.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public class UsersViewHolder extends RecyclerView.ViewHolder {
View mview;
public UsersViewHolder(#NonNull View itemView) {
super(itemView);
mview = itemView;
}
public void setName(String name) {
TextView userNameView = mview.findViewById(R.id.username);
userNameView.setText(name);
}
public void setStatus(String status) {
TextView userStatusView = mview.findViewById(R.id.phone);
userStatusView.setText(status);
}
}

Recyclerview is not showing any data which i have in firebase. Iam able to retrieve the data

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.

Firestore recyclerview

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;
}

How to get document id of the postion of recycler view Item?

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();
}
});

Categories

Resources