Filter in RecyclerView Android
Search & Load recycler view from a public API.
🚀 Hello, In this article, we are going to implement a complete page with a search view & recycler view.
From fetching data to populating recycler view with a list of responses from public URL “https://picsum.photos/v2/list”.
Response of this GET API
[
{
“id”:”0",
“author”:”Alejandro Escamilla”,
“width”:5616,
“height”:3744,
“url”:”https://unsplash.com/photos/yC-Yzbqy7PY",
“download_url”:”https://picsum.photos/id/0/5616/3744"
},
{
“id”:”1",
“author”:”Alejandro Escamilla”,
“width”:5616,
“height”:3744,
“url”:”https://unsplash.com/photos/LNRyGwIJr5c",
“download_url”:”https://picsum.photos/id/1/5616/3744"
}
....
]
Step 1: Initial Setup
Initial project setup & retrofit is available in below source code link made with love, Kotlin & Hilt Injection.
Adding base URL to our Gradle implementation.
buildConfigField
'String', 'BASE_URL', "\"https://picsum.photos/v2/list\""
Step II. Creating Model & Adapter
Here, In the project, the Photos model is created from API response “https://picsum.photos/v2/list”.
Photos.kt
import com.google.gson.annotations.SerializedName
data class Photos(
@SerializedName("author")
var author: String, // Matthew Wiebe
@SerializedName("download_url")
var downloadUrl: String, // https://picsum.photos/id/1025/4951/3301
@SerializedName("height")
var height: Int, // 3301
@SerializedName("id")
var id: String, // 1025
@SerializedName("url")
var url: String, // https://unsplash.com/photos/U5rMrSI7Pn4
@SerializedName("width")
var width: Int // 4951
)
Then, Let’s create an adapter for our recycler view where photosList is a list of data & photosListFiltered is a result of the list we get after filtering.
var photosList: ArrayList<Photos> = ArrayList()
var photosListFiltered: ArrayList<Photos> = ArrayList()
Also to implement search in our recyclerview. We need to implement Filterable in your adapter and override getFilter(): Filter object.
PhotosAdapter.kt
Let’s add PhotosAdapter into our PhotosActivity.We also need to implement SearchView.OnQueryTextListener in our activity/fragment.
PhotosActivity.kt
PhotosViewModel.kt
Step III. Plotting Recyclerview
Here, we observe results from the server and post a value to onResponse, above in activity we observe this response.
Done, All your searches should be working.
Thumps up for more articles with examples.
Thank you.
Good day.