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

China☆狼群 提交于 2019-12-31 03:24:11

问题


** EDITED **

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

  1. Create a new database reference named Tokens (In line with Clients and Workers), and under Tokens;
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!