You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何通过位置获取Firebase的Post Key(报错求助)

解决Firebase RecyclerView适配器中通过位置获取Post Key的问题

嘿,作为刚接触Firebase的新手,遇到这个问题很正常,我来帮你理清思路并解决它!

问题根源

你报错的原因很直接:DatabaseReference类的getRef()方法并没有接受position参数的重载。getRef()要么不带参数(返回当前引用本身),要么接受一个字符串类型的路径参数,用来获取该路径下的引用——它从来不是用来通过列表索引获取节点Key的方法。

正确解决方案

要实现通过RecyclerView的位置获取对应Firebase节点的Key,正确的做法是在读取数据时,将每个节点的Key和数据一起保存到你的Beaches模型类中,之后直接从模型对象中取出Key即可。具体步骤如下:

  1. 修改Beaches模型类,添加Post Key字段
    给Beaches类新增一个用来存储节点Key的字段,并添加对应的getter和setter方法:

    public class Beaches {
        // 你原本的字段
        private String name;
        private String texto;
        private String site;
        private String emissora;
        private String endereco;
        private String url;
        // 新增的Post Key字段
        private String postKey;
    
        // 原本的构造方法、getter和setter...
        
        // 新增的getter和setter
        public String getPostKey() {
            return postKey;
        }
    
        public void setPostKey(String postKey) {
            this.postKey = postKey;
        }
    }
    
  2. 读取Firebase数据时保存节点Key
    在你从Firebase数据库加载数据到beaches列表的代码中(通常在ValueEventListener的onDataChange方法里),把每个节点的Key存入对应的Beaches对象:

    DatabaseReference beachesRef = FirebaseDatabase.getInstance().getReference().child("你的海滩数据节点路径");
    beachesRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<Beaches> beaches = new ArrayList<>();
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                Beaches beach = snapshot.getValue(Beaches.class);
                // 保存当前节点的Key到Beaches对象
                beach.setPostKey(snapshot.getKey());
                beaches.add(beach);
            }
            // 更新适配器数据
            yourAdapter.setBeaches(beaches);
            yourAdapter.notifyDataSetChanged();
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            // 处理错误
        }
    });
    
  3. 在适配器中直接获取Post Key
    回到你的MyAdapter的onBindViewHolder方法,替换掉报错的代码,直接从beaches列表的对应位置获取Beaches对象,再取出Key:

    // 替换原来报错的这一行
    // final String post_key = Database.getRef(position).getKey().toString();
    // 改为:
    final String post_key = beaches.get(position).getPostKey();
    

为什么这个方法可行?

Firebase的节点本身是没有“位置索引”概念的(除非你显式使用排序并保留索引信息),所以直接通过position去数据库引用里找对应的节点是行不通的。而在读取数据时把Key和数据绑定在一起,是最可靠且高效的方式,因为每个节点的Key是唯一且固定的,和你的数据列表位置一一对应。

现在修改完代码后,你就能正常获取到对应位置的Post Key了,后续的点赞等操作也能基于这个Key正常进行。

内容的提问来源于stack exchange,提问作者teste testee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:06:20