且构网

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

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

更新时间:2022-11-25 11:17:02

我建议您使用此方法:

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);
}