如何获取数据库条目Firebase的密钥?

时间:2018-10-24 11:45:45

标签: android firebase firebase-realtime-database

我有一个Firebase数据库

database

密钥是自动生成的。 如何给密钥-LPW2KQ_cF82Bbx-VRXl?

代码

String key = FirebaseDatabase.getInstance()
                        .getReference()
                        .push()
                        .getKey();

还给我一个新的自动生成的密钥。

更新

代码

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                for (DataSnapshot objSnapshot: snapshot.getChildren()) {
                    String key = objSnapshot.getKey();
                    Toast.makeText(Chat.this, key, Toast.LENGTH_SHORT).show();
                }


   }
                @Override
                public void onCancelled(DatabaseError firebaseError) {
                    Log.e("Read failed", firebaseError.getMessage());
                    Toast.makeText(Chat.this, "error", Toast.LENGTH_SHORT).show();
                }
            });
        }
    });

给我一​​个最后个有效密钥 -LP_mib37Ba7uGNVzk3U

如何为我单击的每个条目提供密钥? ?

1 个答案:

答案 0 :(得分:0)

首先创建一个根孩子,然后再使用子孩子。像这样:

用户
   -LP_mib37Ba7uGNVzk3U
   -LP_mib37Ba7uGNVzk3U

尝试:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                for (DataSnapshot objSnapshot: snapshot.getChildren()) {
                    String key = objSnapshot.getKey();
                    Toast.makeText(Chat.this, key, Toast.LENGTH_SHORT).show();
                }


   }
                @Override
                public void onCancelled(DatabaseError firebaseError) {
                    Log.e("Read failed", firebaseError.getMessage());
                    Toast.makeText(Chat.this, "error", Toast.LENGTH_SHORT).show();
                }
            });
        }
    });

希望对您有帮助。