且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将数据从一个节点移动或复制到 Firebase 数据库中的另一个节点

更新时间:2022-11-25 11:13:04

我建议你使用这个方法:

I recomand you to use this method:

public void copyRecord(Firebase fromPath, final Firebase toPath) {
    fromPath.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            toPath.setValue(dataSnapshot.getValue(), new Firebase.CompletionListener() {
                @Override
                public void onComplete(FirebaseError firebaseError, Firebase firebase) {
                    if (firebaseError != null) {
                        System.out.println("Copy failed");
                    } else {
                        System.out.println("Success");
                    }
                }
            });
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {}
    });
}

这是一个副本,而不是您可能看到的移动,因此原件将保留在其原始位置.如果你想删除,你可以在 System.out.println("Success"); 之后的 fromPath 上使用 removeValue() 方法代码>.

This is a copy and not a move as you probably see, so the original will remain at his original place. If you would like to delete, you can use removeValue() method on the fromPath just after the System.out.println("Success");.

(2018 年 5 月 3 日).

这是使用新 Api 的代码.

Here is the code for using the new Api.

private void moveRecord(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);
}