如何更改Firebase数据库中的密钥? [英] How to change a key in firebase database?

查看:109
本文介绍了如何更改Firebase数据库中的密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作社交媒体应用.所有用户数据都是用户名对象的子级. 例如

Im making a social media app. All user data is child of username object. For example

root:
  +users:
    +ricksanchez:
      +name:"Rick Sanchez";
      +email:"rick@sanchez.com";
      +bio:"I'm super smart";
      +followers:
        +follower1:morty;
        +follower2:summer;
      ....

如何在不丢失数据的情况下更改ricksanchez键?

How to change ricksanchez key without losing data?

可以重命名Firebase实时数据库中的关键?

我检查了这个问题,但是我在编码方面还很新.我猜那不是Java.你知道怎么用Java做到吗?

I checked out this question but im quite new in coding.I guess thats not Java.Do you know how to do it in Java?

推荐答案

您不能更改键的名称,例如ricksanchez可以更改为其他名称.没有用于执行此操作的API.如果要更改键的名称,则肯定需要将该特定对象复制到另一个位置,更改名称,然后删除旧记录.但是要在Firebase中临时更改密钥名称是不可能的.

You cannot change the name of a key, let's say ricksanchez to something else. There is no API for doing that. If you want to change the name of a key, you definitely need to copy that particular object to another location, change the name and then delete the old record. But to somply change the name of key is not possible in Firebase.

编辑:根据您的评论,请使用以下方法将一条记录从一个位置复制到另一个位置.

According to your comment, please use the following method to copy a record from a location to another.

private void copyRecord(DatabaseReference fromPath, final DatabaseReference toPath) {
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            toPath.setValue(dataSnapshot.getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isComplete()) {
                        Log.d(TAG, "Success!");
                    } else {
                        Log.d(TAG, "Copy failed!");
                    }
                }
            });
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    fromPath.addListenerForSingleValueEvent(valueEventListener);
}

这篇关于如何更改Firebase数据库中的密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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