Updated 31 May 2023
To show Google Search Result in Android App using Rest API, you can use the Google Rest API to fetch search results and display them in your app.
We are going to use the below Google rest API for a custom search.
1 |
https://www.googleapis.com/customsearch/v1?key=YOUR_API_KEY&cx=SEARCH_ENGINE_ID&q=<SEARCH_TERM> |
YOUR_API_KEY- Go to the Google Cloud Console (https://console.cloud.google.com/), create a new project, enable the Google Search API, and generate an API key.
If you already have a Google API key, then you can use the same.
<SEARCH_TERM>– You have to pass your search keyboard at the place of <SEARCH_TERM>.
SEARCH_ENGINE_ID
– replace with the unique identifier for your custom search engine.
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, ) |
Create one more data class that use as the main response class.
Like-
1 2 3 |
data class SearchResponse( val search: List<SearchResult> ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
OkHttpClient client = new OkHttpClient(); String url = "https://www.googleapis.com/customsearch/v1?key=YOUR_API_KEY&cx=SEARCH_ENGINE_ID&q=QUERY"; Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // Handle request failure } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String responseBody = response.body().string(); // Parse the response JSON to your model clss and extract the search results // Update your UI with the search results } else { // Handle request failure } } }); |
Parse the JSON response and map it to your data class received in the onResponse
method. Extract the search results from the JSON and update your app’s UI accordingly.
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 Google rest Api for the keyword “Test”.
In this blog, we have checked how we can show Google search results in our Android app.
Hope, it will help you.
Thanks for your time.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.