Issue
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(itemsAdapter);
registerForContextMenu(listView);
fstore.child(/*MyFolder1*/).child(/*MyFolder2*/).listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
@Override
public void onSuccess(ListResult listResult) {
for(StorageReference sref : listResult.getItems())
{
items.add(sref.getName()); //<- NOT working
System.out.println("IIIIII: "+sref.getName()); //sref.getName() returns proper value here
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(tabtwoactivity.this, "Fetching failed", Toast.LENGTH_LONG).show();
}
});
itemsAdapter.notifyDataSetChanged();
Why doesn't sref.getName()
get added to the list? All items.add()
statements before and after work properly.
Ignore this part - I need to add some more info to be able to publish the question. I hope this much is enough.
Solution
The Firebase Storage API listAll()
is asynchronous and returns immediately before the results are available. Your callback is invoked some time later, after the results are available. While listAll() is executing, your code does on to immediately render the empty list, and notifyDataSetChanged
ends up doing nothing. Your code needs wait for the results to complete before trying to render any views.
Try instead calling itemsAdapter.notifyDataSetChanged()
from within the onSuccess
callback to force the adapter to render the new results.
fstore.child(/*MyFolder1*/).child(/*MyFolder2*/).listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
@Override
public void onSuccess(ListResult listResult) {
for(StorageReference sref : listResult.getItems())
{
items.add(sref.getName()); //<- NOT working
System.out.println("IIIIII: "+sref.getName()); //sref.getName() returns proper value here
}
itemsAdapter.notifyDataSetChanged();
}
You will probably also want to decide what you want to display before listAll()
is complete, as it might not be as fast as you want.
Answered By - Doug Stevenson
Answer Checked By - Mildred Charles (JavaFixing Admin)