Saturday, September 1, 2012

Implement Google Search (JSON) for Android

Remark@2017-07-3:
This example no more work!
"The Google Web Search API is no longer available. Please migrate to the Google Custom Search API (https://developers.google.com/custom-search/)"

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

Implement Google Search (JSON) for 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, android.os.NetworkOnMainThreadException will be thrown. Refer to the post android.os.NetworkOnMainThreadException.

Finally, we have to modify AndroidManifest.xml to add permission of "android.permission.INTERNET".

package com.example.androidajaxsearch;

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 APIs (JSON) for : " + search_item + "\n";
     parsedResult += "Number of results returned = " + jsonArray_results.length() + "\n\n";
     
     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;
    }
}


<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>


Download the files.

Next:
- Implement Google Search (JSON) for Android, display in WebView.
- Google Search with custom search phase


2 comments:

Anonymous said...

Where is the result??

Ponpoorani Ravichandran said...

Its throwing this error:

04-03 16:14:43.720 20901-20940/com.example.poorani.searchex W/System.err: org.json.JSONException: Value null at responseData of type org.json.JSONObject$1 cannot be converted to JSONObject