0

In my Android Studio Java project, in Firebase Realtime database I am setting favorite foods to the user logged in. Everytime I use setValue, it overwrites the existing entry. I would like to add multiple foods such as in an array.

Here is the code below that is updating the Firebase Realtime database

    FirebaseAuth.getInstance().getCurrentUser();
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    FirebaseDatabase database =  FirebaseDatabase.getInstance();

    String userId = user.getUid();
    User user1 = new User("banana");
    DatabaseReference mRef =  database.getReference().child("Users").child(userId);
    mRef.setValue(user1);

Here is the User java class

public class User {

    public String foods;

    //required default constructor
    public User() {
    }

    public User(String foods) {
        this.foods = foods;
    }

    public String getFoods() {
        return foods;
    }

    public void setFoods(String foods) {
        this.foods = foods;
    }
}

In Firebase this is an example of my JSON response:

{
  "Users" : {
    "ExampleUser1" : {
      "foods" : "banana"
    }
  }
}

Replacing

mRef.setValue(user1);

with

mRef.push().setValue(user1);

seems to get me where I need to go.

{
  "Users" : {
    "ExampleUser1" : {
      "-MZ4Cfec_EFb6i5bUIEl" : {
        "foods" : "banana"
      },
      "-MZ4EJV14CKUvYn9ISJl" : {
        "foods" : "apple"
      }
    }
  }
}

EDIT: This is the solutions I ended up using. Thank you all for your help and comments.

Arrays are not stored as array in the firebase realtime database Handling arrays with firebase realtime database is a bit tricky and they don’t work as expected. Firebase stores them as key value pair. To get the desired result, I used a hash map where I can set the key and value pair. This is the only code needed and I deleted the User class. The string fruit is an example and everytime it is updated, it was added to the database for that user. Duplicate entries are not allowed since I set the value of the fruit to equal the key as well.

    String fruit="banana"
    FirebaseAuth.getInstance().getCurrentUser();
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    FirebaseDatabase database =  FirebaseDatabase.getInstance();

    String userId = user.getUid();
    DatabaseReference mRef =  database.getReference().child("Users").child(userId);

    Map<String, Object> updates = new HashMap<String,Object>();

    updates.put(fruit, fruit);

    mRef.updateChildren(updates);

Here is the JSON response from Firebase realtime database:

{
  "Users" : {
    "UserExample1" : {
      "banana" : "banana",
      "apple" : "apple",
      "orange" : "orange"
    }
  }
}
1
  • While this blog post is many years old, it's recommendations still hold true. Commented Apr 24, 2021 at 19:02

3 Answers 3

1

try update() and see if it works

try this.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a screenshot of JavaScript code, while OP is asking about Android/Java. Also: please don't post screenshots of code, or other textual content. Instead post the actual text, and use the formatting tools of Stack Overflow to mark it up.
0

If you want to store an array of foods, you should model that into your `` first.

public class User {

    public String[] foods;

    //required default constructor
    public User() {
    }

    public User(String[] foods) {
        this.foods = foods;
    }

    public String[] getFoods() {
        return foods;
    }

    public void setFoods(String[] foods) {
        this.foods = foods;
    }
}

Then you can simply set that array to the database:

String userId = user.getUid();
User user1 = new User(new String[] {"banana", "apple"});
DatabaseReference mRef = database.getReference().child("Users").child(userId);
mRef.setValue(user1);

I'd also recommend reading these, as arrays are a common antipattern in Firebase:

Comments

0

Arrays are not stored as array in the firebase realtime database Handling arrays with firebase realtime database is a bit tricky and they don’t work as expected. Firebase stores them as key value pair. To get the desired result, I used a hash map where I can set the key and value pair. This is the only code needed and I deleted the User class. The string fruit is an example and everytime it is updated, it was added to the database for that user. Duplicate entries are not allowed since I set the value of the fruit to equal the key as well.

    String fruit="banana"
    FirebaseAuth.getInstance().getCurrentUser();
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    FirebaseDatabase database =  FirebaseDatabase.getInstance();

    String userId = user.getUid();
    DatabaseReference mRef =  database.getReference().child("Users").child(userId);

    Map<String, Object> updates = new HashMap<String,Object>();

    updates.put(fruit, fruit);

    mRef.updateChildren(updates);

Here is the JSON response from Firebase realtime database:

{
  "Users" : {
    "UserExample1" : {
      "banana" : "banana",
      "apple" : "apple",
      "orange" : "orange"
    }
  }
}

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.