'Moving or copying data from one node to another in firebase database

I am trying to move my data present at one node i.e cart_details/UID to another node orders/UID/order1. I tried different ways of doing it but all seem to be a bit confusing. Is there any built-in functionality or method that could possibly make the job easier? Any help is appreciated.

I have attached the image for the same. IMAGE.



Solution 1:[1]

To solve this, I recommend you using the following lines of code:

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) {
            Log.d("TAG", firebaseError.getMessage()); //Never ignore potential errors!
        }
    });
}

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

Edit: (03 May 2018).

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) {
            Log.d("TAG", firebaseError.getMessage()); //Never ignore potential errors!
        }
    };
    fromPath.addListenerForSingleValueEvent(valueEventListener);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1