我正在尝试访问将我的帖子信息存储在Firebase中的密钥。
我所需要的就是像使用库一样访问Key。

final String TheKey = getRef(position).getkey();


使用自定义RecyclerView时如何执行上述代码?如何像上述代码那样访问密钥?问题是我正在使用不支持getRef()的Custom RecyclerView。我想访问onBindViewHolder中的密钥,在哪里可以找到下面的密钥是我的代码。

@Override
public void onBindViewHolder(@NonNull final viewHolder holder, final int position) {
    final String kkk = List.get(position).getUid();
    Posts posts = List.get(position);
    Picasso.get().load(posts.getPostimage()).placeholder(R.drawable.photo).into(holder.PostImage);
    Picasso.get().load(posts.getProfileimage()).fit().into(holder.PostProfileimage);
    holder.PostUserName.setText(posts.getFullname());
    holder.PostDate.setText(posts.getDate());
    holder.PostTime.setText(posts.getTime());
    holder.PostDescription.setText(posts.getDescription());

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PostsKey = FirebaseDatabase.getInstance().getReference().child("Posts");
            final int postposition = position;
            Toast.makeText(context, "User Clicked at Position "+postposition, Toast.LENGTH_SHORT).show();
           // Toast.makeText(context, ""+kkk, Toast.LENGTH_SHORT).show();
            final String theKey = PostsKey.getRef().getKey();
            Toast.makeText(context, ""+theKey, Toast.LENGTH_SHORT).show();
        }
    });
}

最佳答案

我假设“库是指FirebaseUI,特别是它的适配器,用于在Android视图中显示Firebase Realtime数据库的内容列表。*

您必须执行与FirebaseUI相同的操作,即跟踪键的位置和所有项目的值。 FirebaseUI通过将Firebase中的FirebaseArray存储在列表中,从而在DataSnapshot class中进行处理。

但是,大多数开发人员似乎更喜欢将快照中的值保留在自定义Java类中,以使其适配器更直接地使用它们,在这种情况下,您通常会遇到以下情况:

List<Post> posts;


这里的Post类具有数据库中每个帖子的属性,您可以使用snapshot.getValue(Post.class)之类的属性来获取它。但是由于Post仅具有对象的值,因此您缺少键。

跟踪键的一种非常简单的方法是添加第二个列表:

List<String> keys;


现在,每当您将帖子添加到列表时,您还都将一个键添加到另一个列表。就像是:

posts.add(snapshot.getValue(Post.class));
keys.add(snapshot.getKey());


一旦拥有了两个列表,就可以通过keys中的索引/位置或先在posts中查找帖子,然后通过其索引查找对应的密钥来找到密钥。

另请参阅:


How can I remove specific item from List when data in firebase realtime db is removed?(显示类似的方法)
Get parent key value on click of child in recyclerview from firebase database(显示构建适配器的更多上下文)

10-07 19:39
查看更多