Firebase Retrieve Current Child then Set as Child of another Child Android

后端 未结 1 1409
走了就别回头了
走了就别回头了 2021-01-21 10:41

** EDITED **

I need help with Firebase. What I need to do is:

  1. Create a new database reference named Tokens (In line with
相关标签:
1条回答
  • 2021-01-21 11:22

    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);
    
    0 讨论(0)
提交回复
热议问题