问题
** EDITED **
I need help with Firebase. What I need to do is:
- Create a new database reference named Tokens (In line with Clients and Workers), and under Tokens;
- Create another new database reference based on the child of the current user (e.g. Carpenters, Plumbers, or Electricians)
Current code:
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference tokens = db.getReference(Common.token_table);
Token token = new Token(FirebaseInstanceId.getInstance().getToken());
//if user is already logged in, will update token
tokens.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(token);
Current database
I need this to be like this:
See image
Updated Screenshot
回答1:
To solve this, you need to get the uid of the authenticated user like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Having this uid, you can use it in every place you need across your activity. So to add the tokenId according to your database structure, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String tokenId = FirebaseInstanceId.getInstance().getToken();
rootRef.child("Tokens").child("Carpenters").child(tokenId).setValue(true);
And your database structure will look like this:
Firebase-root
|
--- Tokens
|
--- Carpenters
|
--- "uid1": true
According to your edit, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String tokenId = FirebaseInstanceId.getInstance().getToken();
rootRef.child("Tokens").child("Plumbers").child(uid).child("token").setValue(tokenId);
Final answer:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String tokenId = FirebaseInstanceId.getInstance().getToken();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference workersRef = rootRef.child("Workers");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
if (ds.child(uid).exists()) {
rootRef.child("Tokens").child(ds.getKey()).child(uid).child("token").setValue(tokenId);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
workersRef.addListenerForSingleValueEvent(valueEventListener);
来源:https://stackoverflow.com/questions/49297961/firebase-retrieve-current-child-then-set-as-child-of-another-child-android