如何获得push()键生成我的Firebase? [英] How to get the push() key generated my Firebase?

查看:41
本文介绍了如何获得push()键生成我的Firebase?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从图片中可以看到,我有一个孩子 FreezerItems ,在该孩子下我还有另外两个孩子,它们是Firebase使用 push().我的问题是,如何具体获得密钥 L8i2M4wNUF5wOojaFE .另外,如何将密钥插入到 RecyclerViewAdapter 中.我已经尝试过了:

As you can see from the picture I have a child FreezerItems, and under that child I have two other childs which are randomKeys that Firebase has created by using push(). My question is, how do I specifically get the key L8i2M4wNUF5wOojaFE. Also how do I get that key into my RecyclerViewAdapter. I have tried this:

holder.mDeleteBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mDatabase = FirebaseDatabase.getInstance().getReference().child("FreezerItems");
            String key = mDatabase.push().getKey();
            Toast.makeText(view.getContext(), key, Toast.LENGTH_SHORT).show();
        }
    });

但是所做的只是显示一个带有随机键的Toast,每次我单击按钮时都会改变

But all that ever did was show a Toast with a random key, that changes each time I click on the button

推荐答案

您在代码中所做的就是,每次单击该项目时都会生成一个新ID.您没有使用存储在数据库中的数据库.为了使用已经生成的ID,您需要先存储它.因此,要解决此问题,我建议您将push()方法提供的随机生成的ID存储为模型类的属性.您的数据库结构应如下所示:

What you are doing in your code, is that you are generating each time you click on the item a new id. You are not using the one that is stored in your database. In order to use the id that was already generated once, you need to store it first. So to solve this problem, I recommend you store that random generated id provided by the push() method as a property of your model class. You database structure should look like this:

Firebase-root
    |
    --- FreezerItems
            |
            --- L8i2M4wNUF5wOojaFE
                      |
                      --- date: "3/31/2018"
                      |
                      --- name: "Ice"
                      |
                      --- freezerItemId: "L8i2M4wNUF5wOojaFE"

然后要删除该特定项目,请使用以下代码:

Then to remove that particular item, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference freezerItemsRef = rootRef.child("FreezerItems");
holder.mDeleteBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            freezerItemsRef.child(freezerItems.getId()).removeValue();
        }
    });

其中 freezerItems 是模型类的对象,而 getId()是返回该特定ID的公共获取器.

In which freezerItems is the object of your model class and getId() is a public getter that returns that particular id.

这篇关于如何获得push()键生成我的Firebase?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆