AboSaqr AboSaqr - 1 year ago 138
Android Question

How to get all childs data on ListView - Firebase database

image description here

i need to get all data in Childs and show it in ListView

Every Values in Childs!,The main Child is "XXX-Users" and other Childs is about "Model Phones",, i want get All Date of This Childs on ListView

this is my Activity:

public class xxxxxxx extends AppCompatActivity {ListView listView;
ArrayList<String> usernames = new ArrayList<>() ;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("xxx-Users");


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xxxxxxxxxxxxx);





listView = (ListView) findViewById(R.id.listview00);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,usernames);
listView.setAdapter(arrayAdapter);

myRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {

String value = dataSnapshot.getValue(String.class);
usernames.add(value);
arrayAdapter.notifyDataSetChanged();


}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});


}`**

My Layout

<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:id="@+id/listview00" />

Answer Source

As cricket_007 said, your code doesn't match your data structure. Your listener will fire for the nodes immediately under xxx-Users. But your actual URL values are one level deeper.

One simple way to handler this is to loop over those nested children in onChildAdded():

DatabaseReference myRef = database.getReference("xxx-Users");
myRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
      for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
        String  value = childSnapshot.getValue(String.class);
        usernames.add(value);
      }
      arrayAdapter.notifyDataSetChanged();
    }
    ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download