尽管接收快照并在ArrayList
函数的onDataChange()
中添加数据,此函数仍不返回任何数据,但最后,它返回的大小为0的ArrayList
。
List<ProductEntity> feed_data() {
final List<ProductEntity> feededProducts = new ArrayList<>();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
mDatabase = FirebaseDatabase.getInstance().getReference("/products");
//adding an event listener to fetch values
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
//dismissing the progress dialog
progressDialog.dismiss();
//iterating through all the values in database
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
ProductEntity upload = postSnapshot.getValue(ProductEntity.class);
Log.d("error", "onDataChange: " + upload.about);
feededProducts.add(upload);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Error", "onCancelled: " + databaseError.getMessage());
NestedScrollView root_layout = findViewById(R.id.category_root_layout) ;
Snackbar.make(root_layout, "Internal Error!!", Snackbar.LENGTH_SHORT).show();
}
});
return feededProducts ;
}
最佳答案
onDataChange(DataSnapshot快照)被异步调用。当我们从Firebase取回数据时,将调用该方法。
因此,您的返回feededProducts在onDataChange(DataSnapshot snapshot)方法之前被调用,因此您每次都将返回空列表。
您将必须在onDataChange(DataSnapshot快照)的适配器上调用notifydatasetchanged