Spotz
Spotz

Reputation: 113

Android- (Firebase) How to set structure an ArrayList differently?

Currently, I am trying to develop an app that invites people to an event using firebase.

I have been using arraylist to set invited peoples' list like this:

friend_list = data.getStringExtra("friends_list");
friend_array = new ArrayList<String>(Arrays.asList(friend_list.split(",")));
newEvent.child("invited").setValue(friend_array);

Doing so, set the values on the Database like this:

invited:
        0: "JohnDoe1"
        1: "JohnDoe2"
        2: "JohnDoe3"
        3: "JohnDoe4"

However, I need it to be set like so:

invited:
        JohnDoe1: true
        JohnDoe2: true
        JohnDoe3: true
        JohnDoe4: true

Is there a way to maybe loop it so it becomes set like this? Thanks in advance.

Upvotes: 1

Views: 942

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138834

Because everything in a Firebase database is structured as pairs of key and value, i suggest you passing a map to the setValue() method and not an ArrayList like this:

String friend_list = data.getStringExtra("friends_list");
List<String> friend_array = new ArrayList<>(Arrays.asList(friend_list.split(",")));
Map<String, Boolean> map = new HashMap<>();
for(String s : friend_list) {
    map.put(s, true);
}
newEvent.child("invited").setValue(map);

As you probably see the declaration of the map is outsite the for loop.

This code will solve your problem for sure.

Upvotes: 3

akhilesh0707
akhilesh0707

Reputation: 6899

Try this will help you

String friend_list = data.getStringExtra("friends_list");
List<Map<String,Boolean>> friend_array = new ArrayList<>();
for(String userStr:Arrays.asList(friend_list.split(","))){
    Map<String,Boolean> userMap=new HashMap<>();
    userMap.put(userStr,true);
    friend_array.add(userMap);
}
newEvent.child("invited").setValue(friend_array);

Upvotes: 0

Related Questions