I want to build a method that can accommodate all cases of my query.
so I want to search for an event from my events collection. it can be searched based on filter whether it is free events or not, and also if it needs to search specific event type or show all events regardless of the event type.
I assumed that I can build a query like this, but the result is wrong. is the way I write the query right?
Here the code of my method:
fun searchEventByParameters(onlyFreeEvents: Boolean, startDate: Date, endDate: Date, selectedCity: String, selectedEventType: String, limit: Long, lastDocument: DocumentSnapshot?, completion: (errorMessage:String?, events: ArrayList<Event>?, lastDocument: DocumentSnapshot?) -> Unit) {
val ref = db.collection("events")
lateinit var query : Query
query = ref
.whereEqualTo(FIRESTORE_EVENT_FIELD_CITY,selectedCity)
.whereEqualTo(FIRESTORE_EVENT_FIELD_IS_ACTIVE,true)
.whereEqualTo(FIRESTORE_EVENT_FIELD_HAS_BEEN_APPROVED,true)
if (onlyFreeEvents) {
query.whereEqualTo(FIRESTORE_EVENT_FIELD_PRICE,0)
}
if (selectedEventType == "show specific event type") {
query.whereEqualTo(FIRESTORE_EVENT_FIELD_EVENT_TYPE, selectedEventType)
}
query.whereGreaterThan(FIRESTORE_EVENT_FIELD_DATE_START_TIME,startDate)
.whereLessThan(FIRESTORE_EVENT_FIELD_DATE_START_TIME,endDate)
.orderBy(FIRESTORE_EVENT_FIELD_DATE_START_TIME, Query.Direction.ASCENDING)
.limit(limit)
if (lastDocument != null) {
query.startAfter(lastDocument)
}
query.get()
.addOnSuccessListener { snapshot ->
val eventDocuments = snapshot.documents
if (eventDocuments.isEmpty()) {
completion("Tidak ada event",null,null)
} else {
val lastDocument = snapshot.documents.last()
val eventArray = ArrayList<Event>()
for (document in eventDocuments) {
val eventData = document.data
val event = Event(dataEvent = eventData)
eventArray.add(event)
}
completion(null,eventArray,lastDocument)
}
}.addOnFailureListener {
completion(it.localizedMessage,null, null)
}
}
here is the screenshot of my database
I assume I can chaining the query like that, but the result is weird. no matter I choose the filter, say I want only show only free events or only music event (event type), the result seems always show all the events in the collection, and the pagination is also failed, seems never-ending.