java – How to get document id in In FirestorePagingAdapter?-ThrowExceptions

Exception or error:

I am trying to use the FirestorePagingAdapter to display a list of all users in my firestore database. I am using FirestorePagingAdapter instead of FirestoreRecyclerAdapter to minimize the number of reads as FirestorePagingAdapterdoesn’t read the whole list of documents while FirestoreRecyclerAdapter does. I am able to display the paginated list successfully but I need to implement onClickListener onto it and on click of every item, I need to open another activity which shows a detailed description of the particular user which was clicked. For this, I need to pass the documentId of the clicked user to the next activity.

But unfortunately, FirestorePagingAdapter doesn’t have getSnapshots() method so that I use getSnapshots().getSnapshot(position).getId().

On the other hand, FirestoreRecyclerAdapter has this method which makes fetching the document id a very easy task. Something like this: How to get document id or name in Android in Firestore db for passing on to another activity?

// Query to fetch documents from user collection ordered by name
Query query = FirebaseFirestore.getInstance().collection("users")
                .orderBy("name");

// Setting the pagination configuration
PagedList.Config config = new PagedList.Config.Builder()
                .setEnablePlaceholders(false)
                .setPrefetchDistance(10)
                .setPageSize(20)
                .build();


FirestorePagingOptions<User> firestorePagingOptions = new FirestorePagingOptions.Builder<User>()
                .setLifecycleOwner(this)
                .setQuery(query, config, User.class)
                .build();

firestorePagingAdapter =
                new FirestorePagingAdapter<User, UserViewHolder>(firestorePagingOptions){

                    @NonNull
                    @Override
                    public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                        View view = LayoutInflater.from(parent.getContext())
                                .inflate(R.layout.single_user_layout, parent, false);

                        return new UserViewHolder(view);
                    }

                    @Override
                    protected void onBindViewHolder(@NonNull UserViewHolder holder, int position, @NonNull User user) {
                        holder.setUserName(user.name);
                        holder.setStatus(user.status);
                        holder.setThumbImage(user.thumb_image, UsersActivity.this);


                        holder.mView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent userProfileIntent = new Intent(UsersActivity.this, UserProfileActivity.class);
                                // Need to fetch the user_id to pass it as intent extra
                                // String user_id = getSnapshots().getSnapshot(position).getId();
                                // userProfileIntent.putExtra("user_id", user_id);
                                startActivity(userProfileIntent);
                            }
                        });
                    }
                };
How to solve:

I was able to do this by using SnapshotParser in setQuery method. Through this, I was able to modify the object which I got from the firestore. The documentSnapshot.getId() method returns the document id.

FirestorePagingOptions<User> firestorePagingOptions = new FirestorePagingOptions.Builder<User>()
                .setLifecycleOwner(this)
                .setQuery(query, config, new SnapshotParser<User>() {
                    @NonNull
                    @Override
                    public User parseSnapshot(@NonNull DocumentSnapshot snapshot) {
                        User user = snapshot.toObject(User.class);
                        user.userId = snapshot.getId();
                        return user;
                    }
                })
                .build();

In the User class, I just added another field “String userId” in the User class. The userId field doesn’t exist in my firestore document.
In the onClickListener, I can then directly use user.userId to get the document id and send it to other activity.

###

As you already noticed:

String id = getSnapshots().getSnapshot(position).getId();

Doesn’t work, it works only when using FirestoreRecyclerAdapter. So to solve this, you need to store the id of the document as property of your document. If the id of the document is the id of the user that comes from the Firebase autentication, then simply store that uid. If you are not using the uid, get the id of the document and pass it to the User constructor when creating a new object like this:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
String id = eventsRef.document().getId();
User user = new User(id, name, status, thumb_image);
usersRef.document(id).set(user);

###

Try using this

getSnapshots().getSnapshot(position).getId()

Leave a Reply

Your email address will not be published. Required fields are marked *