How to add and retrieve data into Firebase using Lists/ArrayLists?

10,459

To achieve this please use the following code:

List<String> friends = new ArrayList<>();
friends.add("John");
friends.add("Steve");
friends.add("Anna");

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
for(String friend : friends) {
    rootRef.child("friends").child(friend).setValue(true);
}

Your database will look like this:

Firebase-root
    |
    --- friends
           |
           --- John: true
           |
           --- Steve: true
           |
           --- Anna: true

To get all those names into a List, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference friendsRef = rootRef.child("friends");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> friends = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String friend = ds.getKey();
            friends.add(friend);
        }
        Log.d("TAG", friends);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
friendsRef.addListenerForSingleValueEvent(eventListener);

Your output will be:

[John, Steve, Anna]
Share:
10,459
riazosama
Author by

riazosama

A curious being who wants to drown in the vast ocean of knowledge. Loves to code and in free time, writes. Passionate about Javascript and using it to solve challenges.

Updated on June 04, 2022

Comments

  • riazosama
    riazosama about 2 years

    I've been trying to figure out how to add data to my firebase real time database using Lists or ArrayLists. For example I want to create a list of users who have liked a post and add them in a list/arraylist then upload that list/ArrayLists in my real time database. After that I also want to retrieve the data from firebase.

  • Marlon
    Marlon almost 6 years
    How can you make this so that you don't have to have a boolean value. The friends list would only contain the names.
  • Alex Mamo
    Alex Mamo almost 6 years
    @Marlon You can use an array but is more convenient to use a map.