addaddress.setOnClickListener {
val pincoder = zipcode.text.toString().trim()
val pinCodeList = listOf("201014", "201301")
val productsRef = FirebaseFirestore.getInstance().collection("Pincode")
.document("zipcollect").collection("zipcodes")
productsRef.whereArrayContainsAny("pin_code", pinCodeList).get().addOnCompleteListener {
if (pincoder.equals(it.isSuccessful.toString()) == 0)
{
for (document in it.result!!) {
Log.d(TAG, document.id " => " document.data)
Toast.makeText(this,"We Deliver Here!", Toast.LENGTH_SHORT).show()
}
}
else {
Toast.makeText(this,"We Don't Deliver Here!", Toast.LENGTH_SHORT).show()
}
}
Here's a screenshot of data stored in firestore
CodePudding user response:
You cannot tell Firestore, hey Firestore return me all documents where the pin_code
array contains all elements of pinCodeList
.
To solve this, you might consider using a Map rather than an array. Your document should look like this:"
pin_codes
|
--- code_one: 201014
|
--- code_two: 303007
|
--- code_three: 201301
And then perform a separate in query for each code, that looks like this:
val firstCodeQuery = productsRef.whereIn("pin_codes.code_one", Arrays.asList("201014", "201301"))
val firstTask = firstCodeQuery.get()
Do the same for the second and the third query. If one of the values in the List doesn't exist in the Map, doesn't exist in Map, then simply stop querying. If all are present, simply collect the results on the client using my answer from the following post:
Alternatively, you can perform a whereArrayContains operation for each element in the list.
CodePudding user response:
whereArrayContainsAny can be perform on collection and return list of documents and you are tring to get field.
array-contains-any
Use the array-contains-any operator to combine up to 10 array-contains clauses on the same field with a logical OR. An array-contains-any query returns documents where the given field is an array that contains one or more of the comparison values:
You can read here for more detail about array-contains-any You can perform your action like this
val pincoder = zipcode.text.toString().trim()
FirebaseFirestore.getInstance()
.collection("Pincode")
.document("zipcollect")
.collection("zipcodes")
.document("Am0U....<Fill your doc ref>").get()
.addOnCompleteListener {
it.let {
if (it.isSuccessful && it.result != null) {
val pinCodeList = it.result["pin_code"] as List<String>
if(pinCodeList.contains(pincoder)){
Toast.makeText(this,"We Deliver Here!", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(this,"We Don't Deliver Here!", Toast.LENGTH_SHORT).show()
}
}
}
}
.addOnFailureListener {
AppLog.e("===========", "Data fail " it)
}