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

0

I have an X bank that contains business categories and I want you to manually enter the data into Categories, send a copy to AllBusiness.

IamusingthiscodehoweverIamnotfindingawaytojustpickupthechildren

privatevoidcopyRecord(DatabaseReferencefromPath,finalDatabaseReferencetoPath){ValueEventListenervalueEventListener=newValueEventListener(){@OverridepublicvoidonDataChange(DataSnapshotdataSnapshot){toPath.setValue(dataSnapshot.getValue()).addOnCompleteListener(newOnCompleteListener<Void>(){@OverridepublicvoidonComplete(@NonNullTask<Void>task){if(task.isComplete()){Log.d(TAG,"Success!");
                        } else {
                            Log.d(TAG, "Copy failed!");
                        }
                    }
                });
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {}
        };

        fromPath.addListenerForSingleValueEvent(valueEventListener);
    }
    
asked by anonymous 23.05.2018 / 18:56

1 answer

1

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

See How to get started with Cloud Functions and its function would look 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());
});
    
24.05.2018 / 03:49