To implement Wikipedia search in an Android app, you can use the Wikipedia API to fetch search results and display them in your app.
Check the Wikipedia rest API which we are going to use to get search results from Wikipedia.
1 |
https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=<SEARCH_TERM> |
You have to pass your search keyword at the place of <SEARCH_TERM>
Below are the steps you can follow:
Create a data class to represent the search results:
For example :
1 2 3 4 5 |
data class SearchResult( val title: String, val snippet: String, val pageId: Int ) |
Create a data class to represent the search response:
Like-
1 2 3 4 5 6 7 |
data class SearchResponse( val query: Query ) { data class Query( val search: List<SearchResult> ) } |
Create an interface to define the Wikipedia REST API endpoints:
like-
1 2 3 4 5 6 7 8 9 10 |
interface WikipediaService { @GET("w/api.php") fun search( @Query("action") action: String = "query", @Query("list") list: String = "search", @Query("srsearch") srsearch: String, @Query("format") format: String = "json", @Query("srlimit") srlimit: Int = 10 ): Call<SearchResponse> } |
In this example, we’re using the search
endpoint to fetch search results for the user’s input.
In your activity or fragment, initialize the Retrofit client and create a service instance:
For example:
1 2 3 4 5 6 |
val retrofit = Retrofit.Builder() .baseUrl("https://en.wikipedia.org/") .addConverterFactory(GsonConverterFactory.create()) .build() val wikipediaService = retrofit.create(WikipediaService::class.java) |
In the search buttons OnClickListener
, make a call to the Wikipedia API to fetch search results:
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
val searchText = editText.text.toString() wikipediaService.search(srsearch = searchText).enqueue(object : Callback<SearchResponse> { override fun onResponse( call: Call<SearchResponse>, response: Response<SearchResponse> ) { // Process the search results and display them in your UI val searchResults = response.body()?.query?.search ?: emptyList() // ... } override fun onFailure(call: Call<SearchResponse>, t: Throwable) { // Handle API call failure } }) |
Process the search results returned by the API call and display them in your UI. You can use a RecyclerView
to display the search results as a list.
To display the result we use RecyclerView
and bottom sheet.
Like:
In the below image, you can check the JSON response of Wikipedia rest Api for the keyword “Test”
Conclusion
In this blog, we have checked how we can show Wikipedia search results in our Android app.
Hope, it will help you.
Thanks for your time.