0

I have a modal class PlayerDetails:

public class PlayerDetails{
    @ServerTimestamp
    Date regDate;
    boolean hasPlayed;
    ArrayList<Integer> optionSkipped;

    PlayerDetails();

    PlayerDetails(Date regDate, boolean hasPlayed , ArrayList<Integer> optionSkipped){
            this.regDate = regDate;
            this.hasPlayed = hasPlayed;
            this.optionSkipped = optionSkipped;

     }
} 

I want to store [-1,-1,-1,-1] as default of optionSkipped in firestore document field. Like thisenter image description here

I present in Firstore database my field optionSkipped is null

I am inserting data in Firstore like this:

PlayerDetails details=new PlayerDetails(null,false,null);
databaserefrence.collection("game")
.document("game1")
.set(details)
.addOnCompleteListener
..........................
............etc

After adding [-1,-1,-1,-1] ArrayList in Firestore.

I want to update the same array later, like this perhaps [0,0,-1,-1].

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

1

When you create the following object using:

PlayerDetails details=new PlayerDetails(null,false,null);

It means that you let Firebase servers assign the regDate field a Firestore timestamp value, for the hasPlayed field you assign the value of false, and for the optionSkipped you assign null.

If you want your optionSkipped field to hold for example an array with four elements:

[-1, -1, -1, -1]

Then you should pass a list as the last argument to the constructor when you create an object of class:

List<Integer> optionSkipped = Arrays.asList(-1, -1, -1, -1);    
PlayerDetails details=new PlayerDetails(null,false,optionSkipped);

Right after that, the document will look like this:

$docId
 |
 --- regDate: March 14, 2023...
 |
 --- hasPlayed: false
 |
 --- optionSkipped: [-1, -1, -1, -1]

If you later want to update the optionSkipped array with other values using FieldValue#arrayUnion(), then please note that according to the official documentation for updating elements in an array:

You can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present. arrayRemove() removes all instances of each given element.

As I see in your question, you need to add duplicate elements as in the following example:

[0, 0, -1, -1]

So to solve this, I recommend you check my answer from the following post:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193