How to copy children from one node to another node - Android with Firebase

Asked

Viewed 137 times

1

I have an X bank that contains categories of companies and I want you to enter the data manually in Categories, send a copy to Allempresas.

inserir a descrição da imagem aqui

I’m using this code but I’m not finding a way to just get the kids

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

1 answer

1


I suggest you make this copy through a Cloud Function. This is because Cloud Functions run on the Cloud, while your code will run on your device. What if the user closes the app before the copy is finished? You will have the database with missing or incorrect data.

Behold Getting started with Cloud Functions and its function would be like this:

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());
});
  • this function I will have to create for each company? or will copy all academy children, food etc?

  • Will copy all children from each category. This is the only function you will create.

  • You’re the man! Thank you so much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.