如何通过 Firebase 数据库填充 ExpandableListView 子视图?

How can I populate an ExpandableListView child views through Firebase database?

我想用 Firebase 数据库中的值填充我的可扩展列表视图。我可以静态地向视图添加数据,但不能通过 Firebase。

这是我的代码:

public class ExpandableListitems {
public List<String> food;

public HashMap<String, List<String>> getData() {
    final HashMap<String, List<String>> expandableListDetail = new HashMap<String, List<String>>();



    //getting fooditems from database
    FirebaseDatabase firebaseDatabasefighter = FirebaseDatabase.getInstance();
    DatabaseReference databaseReferencefighter = firebaseDatabasefighter.getReference("food").child("food_details");
    ValueEventListener valueEventListenerfighter = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {

                food = new ArrayList<String>();
                String value = String.valueOf(ds.getValue());


                food.add(value);

                Log.i("vipan",value);
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    };
    databaseReferencefighter.addValueEventListener(valueEventListenerfighter);


    food.add("milk");
    food.add("dahi");
    food.add("paratha");
    food.add("aaloo");


   expandableListDetail.put("FoodItems", food);
    return expandableListDetail;

我的数据库如下所示:

  food

food_details: “2% 脱脂牛奶”

我想将此 food_details 值添加到 listview 的视图中 但不能,所以 far.How 我可以吗实现这个?

您现在不能 return 尚未加载的内容。换句话说,你不能简单地 return expandableListDetail HashMap<String, List<String>> 其中包含作为方法结果来自数据库的字符串列表,因为由于异步,此列表将始终为 empty此方法的行为。这意味着当您尝试 return 结果时,数据尚未从数据库加载完毕,这就是无法访问的原因。

一个快速解决这个问题的方法是只在 onDataChange() 方法中使用 food 列表,否则我建议你从这个 中看到我的答案的最后一部分 in which I have explained how it can be done using a custom callback. You can also take a look at this video 以便更好地理解。