Adding Google Search To Your App

Search is a core user feature on Android. Users should be able to search any data that is available to them, whether the content is located on the device or the Internet. To help create a consistent search experience for users, Android provides a search framework that helps you implement search for your application.

The search framework does not provide APIs to search your data. To perform a search, you need to use APIs appropriate for your data. For example, if your data is stored in an SQLite database, you should use the android.database.sqlite APIs to perform searches.

Also, there is no guarantee that a device provides a dedicated SEARCH button that invokes the search interface in your application. When using the search dialog or a custom interface, you must provide a search button in your UI that activates the search interface.

Android’s built-in search features offer apps an easy way to provide a consistent search experience for all users. There are two ways to implement search in your app depending on the version of Android that is running on the device. One is adding search with SearchView, which was introduced in Android 3.0, while maintaining backward compatibility with older versions of Android by using the default search dialog provided by the system. and the other is search using Google Search API of JSON.

In this exercise, we search using Google Search API of JSON format. The item to be searched is fixed “android”, and the query is http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=android

The method sendQuery(String) send the query to Google Search API, the returned result is a string in JSON format.

The method ParseResult(String) parse the JSON result to string.

We have to implement a AsyncTask, JsonSearchTask, to do the jobs in background. Otherwise, NetworkOnMainThreadException will be thrown.
Steps:

1.) Create a new android project naming AndroidSearch.
2.) Modify AndroidManifest.xml to add permission of “android.permission.INTERNET”.

 

package com.example.androidsearch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

String search_url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String search_item = "android";
String search_query = search_url + search_item;

TextView textResult;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textResult = (TextView)findViewById(R.id.result);

new JsonSearchTask().execute();
}

private class JsonSearchTask extends AsyncTask<Void, Void, Void>{

String searchResult = "";

@Override
protected Void doInBackground(Void... arg0) {

try {
searchResult = ParseResult(sendQuery(search_query));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}

@Override
protected void onPostExecute(Void result) {

textResult.setText(searchResult);

super.onPostExecute(result);
}

}

private String sendQuery(String query) throws IOException{
String result = "";

URL searchURL = new URL(query);

HttpURLConnection httpURLConnection = (HttpURLConnection) searchURL.openConnection();

if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader,
8192);

String line = null;
while((line = bufferedReader.readLine()) != null){
result += line;
}

bufferedReader.close();
}

return result;
}

private String ParseResult(String json) throws JSONException{
String parsedResult = "";

JSONObject jsonObject = new JSONObject(json);
JSONObject jsonObject_responseData = jsonObject.getJSONObject("responseData");
JSONArray jsonArray_results = jsonObject_responseData.getJSONArray("results");

parsedResult += "Google Search for : " + search_item + "n";
parsedResult += "Number of results returned = " + jsonArray_results.length() + "nn";

for(int i = 0; i < jsonArray_results.length(); i++){
JSONObject jsonObject_i = jsonArray_results.getJSONObject(i);
parsedResult += "title: " + jsonObject_i.getString("title") + "n";
parsedResult += "content: " + jsonObject_i.getString("content") + "n";
parsedResult += "url: " + jsonObject_i.getString("url") + "n";
parsedResult += "n";
}
return parsedResult;
}
}

 

 

2.) Write following into main.xml:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#A0A0A0">
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

</ScrollView>
</LinearLayout>

 

 

OutPut

json1