Search code examples
javaandroidfirebasefirebase-realtime-databasefirebaseui

Get key value from specific userID firebase recycler adapter


I want to get the key value shown as the image below. I'm using firebase recycler adapter to retrieve the data which is from the key, but right now I want to get the key value.

enter image description here

Right now the code I'm using the retrieve data only this .

 private void setFirebaseRecyclerAdapterKarangan() {
        firebaseRecyclerOptionsKarangan = new FirebaseRecyclerOptions.Builder<UserAlphaKaranganClick>()
                .setQuery(databaseReference.child("userAlphaKaranganClick").child(userUid), UserAlphaKaranganClick.class)
                .build();

    firebaseRecyclerAdapterKarangan = new FirebaseRecyclerAdapter<UserAlphaKaranganClick, UserAlphaActivityLogKaranganViewHolder>(firebaseRecyclerOptionsKarangan) {
        @Override
        protected void onBindViewHolder(@NonNull final UserAlphaActivityLogKaranganViewHolder holder, final int position, @NonNull final UserAlphaKaranganClick model) {
            //We need to convert to become string since it is from long
            holder.getTextViewClick().setText(String.valueOf(model.getClick()));
            holder.getTextViewLike().setText(String.valueOf(model.getLike()));
        }

        @NonNull
        @Override
        public UserAlphaActivityLogKaranganViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_alpha_activity_log_karangan_item, viewGroup, false);
            return new UserAlphaActivityLogKaranganViewHolder(view);
        }
    };

    //Display
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
    linearLayoutManager.setStackFromEnd(true);
    linearLayoutManager.setReverseLayout(true);
    firebaseRecyclerAdapterKarangan.startListening();
    recyclerView2.setAdapter(firebaseRecyclerAdapterKarangan);
    recyclerView2.setLayoutManager(linearLayoutManager);
}

Solution

  • Inside the onBindViewHolder method add the following:

    String key = firebaseRecyclerAdapterKarangan.getRef(position).getKey();
    

    getKey() will retrieve the reference of this snapshot which is in the random ID.