[英]How can I populate an ExpandableListView child views through Firebase database?
I want to populate my expandable list view with the values from Firebase database. 我想用Firebase数据库中的值填充可扩展列表视图。 I am able to add data to views statically but through Firebase not.
我能够将数据静态添加到视图中,但不能通过Firebase添加。
This is my code for that: 这是我的代码:
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;
And my database looks like this: 我的数据库如下所示:
food
food_details: "2% Fat Milk" food_details:“ 2%脂肪牛奶”
i want to add this food_details value into the listview's view but unable so far.How can i implement this? 我想将此food_details值添加到listview的视图中,但到目前为止无法执行。我该如何实现呢?
You cannot return something now that hasn't been loaded yet. 您现在无法返回尚未加载的内容。 With other words, you cannot simply return the
expandableListDetail HashMap<String, List<String>>
which contains a list of strings that is coming from the database as a result of a method because this list will always be empty
due the asynchronous behaviour of this method. 换句话说,您不能简单地返回
expandableListDetail HashMap<String, List<String>>
,其中包含作为方法的结果来自数据库的字符串列表,因为由于该列表的异步行为,该列表将始终为empty
方法。 This means that by the time you are trying to return that result, the data hasn't finished loading yet from the database and that's why is not accessible. 这意味着,当您尝试返回该结果时,数据尚未从数据库中完成加载,因此无法访问。
A quick solve for this problem would be to use the food
list only inside the onDataChange()
method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. 一个快速的解决这个问题是使用的
food
里面只有列表onDataChange()
方法,否则我建议你看我anwser从这个最后部分职位中,我已经解释了如何可以使用自定义的回调来完成。 You can also take a look at this video for a better understanding. 您也可以观看此视频 ,以更好地理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.