Spotz
Spotz

Reputation: 113

Android- Firebase How to assign a child value under each ArrayList value?

I am trying to make an event sorter app. I'm trying to grab the friends arraylist from the database, and add the event_key under each friend value in the database.

final ArrayList<String> friends= new ArrayList<String>();
hello.addListenerForSingleValueEvent(new ValueEventListener() {
             @Override
             public void onDataChange(DataSnapshot dataSnapshot) {

                 for (DataSnapshot dsp : dataSnapshot.getChildren()) {
                     friends.add(String.valueOf(dsp.getKey())); 
                 }

                 mDatabaseUserEvents.child(invited_list).child(event_key).setValue(true);
             }

             @Override
             public void onCancelled(DatabaseError databaseError) {

             }
         });

However, I get an error saying that ArrayList is not compatible.

The database structure I am trying to aim for is this:

Events:
       -User1:
              -event_key:true
       -User2:
              -event_key:true

I am pretty sure I need to use a for loop, but confused on how to achieve it. Thanks!

Upvotes: 0

Views: 456

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Because Firebase is a NoSQL database, it is structured as pairs of key and values. So every child is a Map and not an ArrayList. It's true that you can get a value from the database and store into an ArrayList but not in the way you do, because of the asynchronous behaviour of onDataChange() method, your friends ArrayList will always be empty. This is happening because onDataChange() method is called even before you are trying to add those values to that ArrayList.

If you want to set true for all the event_key coresponding to each user and assuming that Events node is a direct child of Firebase-database, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference eventsRef = rootRef.child("Events");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String userKey = ds.getKey();
            Log.d("TAG", userKey);
            eventsRef.child(userKey).child("event_key").setValue(true);
        }
    }

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

Upvotes: 2

Related Questions