In the Open Event Android App searching events from the list of hundreds of events that are stored in the server is indeed an important task. As in the future there will be more events and the user might not be able to see a particular event that he might want to attend. So let’s see how the searching functionality was implemented in the app.
The API endpoint which we are using looks something like this
This endpoint returns all the events whose “name” field contains the words “Test Event” in ascending order and since the “ilike” operator is used the results are not case sensitive.
The following lines are used to send a GET request to the server. We have two query parameters that is sort and filter. They are required so that we can get the list of events in ascending order and filter out the correct events. The function returns a list of events.
Now this is where the magic happens. This function returns the list of events that have the same name as the user has searched and stores it in the database. So all these events are stored offline as well.
We are using a SearchView to search the events. What happens here is that the user searches somethings and presses search, onQueryTextSubmit method gets called and it passes the search query to the ViewModel and loads the events.
To add the search icon in the toolbar we just need to add the following code in the XML file. We specify the id of the searchView so that we can reference it in our code. The value of showAsAction is “always” which means the searchView icon will always be visible in the toolbar.
That’s all that we require to search events in the app.
- SearchView Official Android Documentation https://developer.android.com/training/search/setup
- ViewModel Official Android Documentation https://developer.android.com/topic/libraries/architecture/viewmodel
- Retrofit Official Documentation http://square.github.io/retrofit/