Allan
Allan

Reputation: 25

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.

Upvotes: 0

Views: 4080

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138834

To solve this, I recommend you use 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) {
                        Log.d(TAG, "Copy failed!");
                    } else {
                        Log.d(TAG, "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 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) {
            Log.d("TAG", databaseError.getMessage()); //Never ignore potential errors!
        }
    };
    fromPath.addListenerForSingleValueEvent(valueEventListener);
}

Upvotes: 2

Related Questions