简体   繁体   中英

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. I am able to add data to views statically but through Firebase not.

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"

i want to add this food_details value into the listview's view but unable so far.How can i implement this?

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. 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. You can also take a look at this video for a better understanding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM