Good morning,
I am trying to get data from the Firestore and add those to my Listview. Unfortunately, it doesn't work and I am not sure why. The code runs but doesn't add any entries to my Listview. My code looks as following:
public void createListViewcontent() {
listView = findViewById(R.id.mylistview);
final ArrayList<String> Listviewcontent= new ArrayList<String>();
db.collection("ok")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Listviewcontent.add(document.getId());
Toast.makeText(kk.this, document.getId() + " => " + document.getData(), Toast.LENGTH_SHORT).show();
Toast.makeText(kk.this, "weird", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(kk.this, "failure", Toast.LENGTH_SHORT).show();
}
}
});
ArrayAdapter<String> arrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Listviewcontent);
listView.setAdapter(arrayAdapter);
Does anyone have an idea?
Best regards androidbeginner
You are getting the results from the database, you are adding them to the list, but you do not notify the adapter. That's the whole idea, you get the items and inform the adapter right after that. So should simply add the following line of code:
arrayAdapter.notifydatasetchanged();
Right after the for loop ends:
db.collection("ok")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Listviewcontent.add(document.getId());
Toast.makeText(kk.this, document.getId() + " => " + document.getData(), Toast.LENGTH_SHORT).show();
Toast.makeText(kk.this, "weird", Toast.LENGTH_SHORT).show();
}
arrayAdapter.notifydatasetchanged(); //Notify the adapter
} else {
Toast.makeText(kk.this, "failure", Toast.LENGTH_SHORT).show();
}
}
});
You can see a working example in my answer from the following post: