0

I have an X DB that contains categories of companies and I want to get the children of the Categorias and send a copy to AllEmpresas

my firebase https://i.stack.imgur.com/ynbzg.jpg

I'm using this code but i don't know how to implement

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);
    }
ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56
Harrison
  • 1
  • 2
  • Possible duplicate of [Failed to parse note when adding Firebase.CompleteListener](https://stackoverflow.com/questions/50147779/failed-to-parse-note-when-adding-firebase-completelistener) – Alex Mamo May 24 '18 at 06:03

2 Answers2

2

Once implemented, Your code will cause a loop which will be infinite. This is the right way for it to function correctly.

private void copyRecord(DatabaseReference fromPath, final DatabaseReference toPath) {
    fromPath.addListenerForSingleValueEvent(new ValueEventListener()  {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            toPath.setValue(dataSnapshot.getValue().toString()).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    Log.d(TAG, "Success!");
                }
            });
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
}
Lucem
  • 2,912
  • 3
  • 20
  • 33
0

A better approach

I chose to use Cloud Function and it works great!

Thank's guys for the support.

const functions = require('firebase-functions');

const admin = require('firebase-admin'); //Importar o Admin SDK para escrever dados na database
admin.initializeApp(functions.config().firebase);   

exports.copiarEmpresas = functions.database.ref('/Categorias/{categoria}/{empresa}')
    .onWrite((change, context) => {
        var snapshot = change.after;
        return admin.database().ref('AllEmpresas').child(snapshot.key).set(snapshot.val());
});
Harrison
  • 1
  • 2