Ahmed El-Nakib
Ahmed El-Nakib

Reputation: 179

how to get first child node in realtimedatabase firebase

my database in realtimedatabase

i have tried to get this child's data only and show it in listview by substring from start word to [to] word by using addValueEventListener but in all way's he get an error in onDataChange method ...

i tried to get this data by this code

FirebaseDatabase.getInstance().getReference().child("chats").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    for(DataSnapshot ds : dataSnapshot.getChildren()) {
                        if (ds.getValue().toString().contains(getIntent().getStringExtra("displayName"))) {
                            chat_childs += ds.getValue().toString() + "\n";
                            String doctorName = chat_childs.substring(0, chat_childs.lastIndexOf("to"));
                            allDoctorsModels.add(new AllDoctorsModel(doctorName, "", ""));
                        }
                    }
                    allDoctorsAdapter = new AllDoctorsAdapter(patient_message.this,allDoctorsModels,getIntent().getStringExtra("displayName"));
                    recyclerView.setAdapter(allDoctorsAdapter);
                    progressDialog.dismiss();
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

Upvotes: 1

Views: 925

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

To get the first child Doc Ahmed Rafaat to Pat Ahmed El-Nakib, do the following:

FirebaseDatabase.getInstance().getReference().child("chats").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                  String key = ds.getKey();
                  if(key.contains("Doc Ahmed Rafaat to Pat Ahmed El-Nakib")
                   {
                      String doctorName = key.subString(4,16);
                      allDoctorsModels.add(new AllDoctorsModel(doctorName, "", ""));
                   }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

First loop inside of the direct children of chats, then retrieve all the keys and check if the key contains Doc Ahmed Rafaat to Pat Ahmed El-Nakib then using subString on the variable key you can retrieve the name Ahmed Rafaat.

Upvotes: 1

Related Questions