Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add array value in Firebase

I want to add some certain data to a Firebase as arrays. Example:

groups : ['a','b','c']

How can I add and read data in Firebase from Android?

like image 552
Doge Avatar asked Sep 11 '26 07:09

Doge


1 Answers

When you have a structure like that, you actually shouldn't be using an array to model it. It seems much more like a set in my eyes.

In the Firebase Database sets are best modeled as keys, since that automatically guarantees that items are unique. So your structure then becomes:

groups: {
  "a": true,
  "b": true,
  "c": true
}

The true values are just markers, since Firebase won't allow you to store keys without a value.

Now to add a group to this, you'd use Firebase's setValue() function:

DatabaseReference root = FirebaseDatabase.getInstance().reference();
DatabaseReference groupsRef = root.child("groups");
groupsRef.child("d").setValue(true);
like image 165
Frank van Puffelen Avatar answered Sep 12 '26 20:09

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!