Mohamed Elloumi Mohamed Elloumi - 16 days ago 11
Android Question

Populate Gridview With Firebase Using Hashmap

I'm trying to populate my gridview using Hashmap but i'm facing this problem:

using this code to get data (books info) from firebase and populate my gridview I get an empty grid view:

mDatabasee = FirebaseDatabase.getInstance().getReference();
mDatabasee.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.child("Items").getChildren()) {

Item person = postSnapshot.getValue(Item.class);
Log.d("picture",person.getBookImage());
hm.put(postSnapshot.getKey().toString(),person.getBookImage());
String number = String.valueOf(hm.size());
Log.d("count",number);


this Log.d return count : 1 exactly like I have in firebase

}
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());

}

}

public void onCancelled(DatabaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});

String number = String.valueOf(hm.size());
Log.d("css css css",number);
gridView.setAdapter(new ImageAdapter(this, hm));


the last Log.d return
"css css css 0"
so it's normal that I'm receiving an empty grid view, to make sure i have added manually 1 book so the new code become:

hm.put("-KWyZJM9GhhTe1PzuJMh","http://books.google.com/books/content?id=aJeTCgAAQBAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api");
String number = String.valueOf(hm.size());
Log.d("css css css",number);
gridView.setAdapter(new ImageAdapter(this, hm));

Answer

You must notify the adapter of changes.

adapter = new ImageAdapter(this, hm); // Stored as member variable
gridView.setAdapter(adapter);

within the firebase method, adapter.notifyDataSetChanged();

Comments