anfehernandez94 anfehernandez94 - 1 month ago 15
Android Question

Show a database of Firebase in a arraylist from a fragment

I call a fragment, and this has a base from Firebase for to fill a list, and I'm calling it so:

private void getClients() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("client");
myRef.addValueEventListener(valueEventListener);
}

ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot){
readClients(dataSnapshot);
}
@Override
public void onCancelled(DatabaseError error) {}
};

private void readClients(DataSnapshot dataSnapshot) {
for(DataSnapshot dss: dataSnapshot.getChildren()){
Client client = dss.getValue(Client.class);
listClients.add(client);
}
}


I tried to call getClients from the createView, onStart and onResume, but don't show me the list with the data, only when I minimize this app or I change for other app, and I open again the app, the list shows the data. How do I call or show the database, inmediately the fragment appears?

Answer

call listviewAdapter.notifyDataSetChanged() on listview adapter after for loop.

your adapter for the listview is set before the listClients populates itself, and therefore your list is empty.

The notifyDataSetChanged() will cause the listview to refresh itself with the new values populated in listClients

private void readClients(DataSnapshot dataSnapshot) {
   for(DataSnapshot dss: dataSnapshot.getChildren()){
       Client client = dss.getValue(Client.class);
       listClients.add(client);
   }
listviewAdapter.notifyDataSetChanged()
}

Check the docs out for more info