0

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.

My Firebase structure. enter image description here

I defined Firebase db in main Activity:

  FirebaseDatabase db;

in 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.

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?

serkan stack
  • 155
  • 5
  • 15

2 Answers2

1

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());
Andrej Jurkin
  • 2,216
  • 10
  • 19
0

Create a DatabaseReference in your activity:

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(); 
}});
Gavine Joyce
  • 389
  • 3
  • 8