niel rhuver yvan
niel rhuver yvan

Reputation: 43

Firestore query array

database enter image description here

If I remove the .whereArrayContainsAny("ItemID", Arrays.asList(onCart)) the statement, there is no error and it retrieves all the documents in a collection, but that is not what I want, I want to retrieve only the documents with ItemID value that is also in the onCart list onCart is from the intent of the prev activity.

error msg: java.lang.IllegalArgumentException: Invalid data. Nested arrays are not supported"

@Override
protected void onStart() {
    super.onStart();
    List<String> onCart=getIncomingIntent();
   
    loadCart(onCart);
}

private void loadCart(List<String> onCart) {
    db.collection("Items")
            .whereArrayContainsAny("ItemID", Arrays.asList(onCart))
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(TAG, document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });
}


private List<String> getIncomingIntent() {
    if (getIntent().hasExtra("checkOut")) {
        return getIntent().getStringArrayListExtra("checkOut");
    }
    return null;
}}

Upvotes: 0

Views: 194

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138804

If i remove the .whereArrayContainsAny("ItemID", Arrays.asList(onCart)) statement, there is no error and it retrieves all the documents in a collection

That's the expected behavior since calling .collection("Items") along with .get() will return all documents within Items collection. However, when adding a call to:

.whereArrayContainsAny("ItemID", Arrays.asList(onCart))

It means that you are looking for every document where the ItemID field is an array that contains one of the elements that exist in the onCart array. This is actually no possible because your ItemID property is a String and not an array:

enter image description here

See the double quotes? If you need the functionality that the whereArrayContainsAny() method provides, you should change your ItemID property to be of type array. If you only want to check the values of your onCart array against your String property ItemID, then you should simply use:

.whereIn("ItemID", Arrays.asList(onCart));

This query returns every document where the ItemID field is set to one of the elements that exist in the onCart array.

Upvotes: 1

Related Questions