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.
Asked
Modified
4 years, 3 months ago
Viewed
12k times
Part
of Mobile Development and Google Cloud Collectives
2 Answers
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]
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