Ashish
Ashish

Reputation: 371

Shortest Query of Firebase in Android?

I need to check if conversation child is exist.

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("users").child(senderId);
    rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            if (snapshot.hasChild("conversations")) {
                if (snapshot.child("conversations").hasChild(receiverId)) {
                    ConversationLocationModel conversationModel = snapshot.child("conversations").child(receiverId).getValue(ConversationLocationModel.class);
                    roomId = conversationModel.getLocation();
                    getAllMessage();
                } else {
                    addinLocation();
                }
            } else {
                addinLocation();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });

Currently I am using above code to check if child has exist i do not want to check every time so how it can be possible if there is any child exist is there any query for checking child existence.

Upvotes: 0

Views: 42

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80944

If you want to check if any child exists, then you can do this:

 DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("users").child(senderId).child("conversations");
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        if (snapshot.exists()){

          //checks if this snapshots exists
      }else{

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

You can change it depending on your database. But the above will check child("users").child(senderId).child("conversations") if conversations exists then it will enter it and see all its children.

Upvotes: 2

Related Questions