5

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.

2 Answers 2

5

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]
Sign up to request clarification or add additional context in comments.

2 Comments

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

I just make clarification. Do you want to manually add user list that liked post? This seems odd for me generally users individually liking post then update post like rate with users id whose like that post in server After you show it for user who display that post. Here some documents for read and write operation in firebase link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.