简体   繁体   English

如何为Firebase检索实时数据库的子元素

[英]How to retrieve child element of realtime database for Firebase

I am making a chat app, I did chat function successfully. 我正在制作一个聊天应用程序,我成功完成了聊天功能。 Now, I want to prevent duplicated username. 现在,我要防止重复的用户名。 So I need child element of Datasnapshot key. 所以我需要Datasnapshot键的子元素。

My Firebase structure. 我的Firebase结构。 在此处输入图片说明

I defined Firebase db in main Activity: 我在主要活动中定义了Firebase db:

  FirebaseDatabase db;

in onCreate 在onCreate中

db=FirebaseDatabase.getInstance();

DatabaseReference dbref = db.getReference("Slitherio 1");
dbref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Iterable<DataSnapshot> keys = dataSnapshot.getChildren();
        for(DataSnapshot key :keys){

            Log.d("key",key.getValue().toString());

        }

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

key.getValue().toString() brings msg and name pairs. key.getValue().toString()带来味精和名称对。

01-21 19:18:57.168 15747-15747/gc.guideforslitherionohacknocheats D/key: {msg=hey, name=admin}
01-21 19:18:57.168 15747-15747/gc.guideforslitherionohacknocheats D/key: {msg=hello, name=SlitherP}
01-21 19:18:57.168 15747-15747/gc.guideforslitherionohacknocheats D/key: {msg=h, name=harry}
01-21 19:18:57.168 15747-15747/gc.guideforslitherionohacknocheats D/key: {msg=d, name=harry}
01-21 19:18:57.168 15747-15747/gc.guideforslitherionohacknocheats D/key: {msg=s, name=s}
01-21 19:18:57.168 15747-15747/gc.guideforslitherionohacknocheats D/key: {msg=d, name=d}
01-21 19:18:57.168 15747-15747/gc.guideforslitherionohacknocheats D/key: {msg=d, name=d}
01-21 19:18:57.168 15747-15747/gc.guideforslitherionohacknocheats D/key: {msg=selam, name=s}
01-21 19:18:57.168 15747-15747/gc.guideforslitherionohacknocheats D/key: {msg=ms, name=n}

But I want to bring just name of children elements. 但是我只想带子元素的名称 How to retrieve name of children elements? 如何检索子元素的名称

Create Message class 创建消息类

public class Message {
    private String msg;
    private String name;

    // Add getters and setters
}

Get value as Message 通过消息获取价值

Message message = key.getValue(Message.class);
Log.d("key", message.getName());

Create a DatabaseReference in your activity: 在您的活动中创建一个DatabaseReference:

DatabaseReference yourDBRef = FirebaseDatabase.getInstance().getReference("ChildName");
//If you have more than one child in your firebase database.
DatabaseReference refwithinref = yourDBRef.child("ChildName1"); 

yourDBRef.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(DataSnapShot datasnapshot){
      String sample = datasnapshot.getValue(String.class);
      //Print the value of the child.
      Toast.makeText(getApplicationContext(),""+sample,Toast.LENGTH_SHORT).show(); 
}});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM