Sunday, September 2, 2012

Implement Google Search (JSON) for Android, display in WebView.

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/)"

Last exercise demonstrate how to "Implement Google Search (JSON) for Android". With little bit modification on the parsed result format, it can be display at WebView as HTML easily.

Implement Google Search (JSON) for Android, display in WebView.


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.webkit.WebView;

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;

 WebView webView;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        webView = new WebView(this);
        setContentView(webView);
        
        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) {

   webView.loadData(searchResult, 
         "text/html", 
         "UTF-8");
   
   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 : <b>" + search_item + "</b><br/>";
     parsedResult += "Number of results returned = <b>" + jsonArray_results.length() + "</b><br/><br/>";
     
     for(int i = 0; i < jsonArray_results.length(); i++){
      
      JSONObject jsonObject_i = jsonArray_results.getJSONObject(i);
      
      String iTitle = jsonObject_i.getString("title");
      String iContent = jsonObject_i.getString("content");
      String iUrl = jsonObject_i.getString("url");
      
      parsedResult += "<a href='" + iUrl + "'>" + iTitle + "</a><br/>";
      parsedResult += iContent + "<br/><br/>";
     }
     
     return parsedResult;
    }
}


Note:
- No layout file needed in this exercise.
- "android.permission.INTERNET" id needed in AndroidManifest.xml.

Download the files.

Next:
- Google Search with custom search phase


3 comments:

  1. The number of results returned is always 4.

    Why is it so?

    and there is one more problem......
    JSON Array will contain the contents of only the current page.....but there are still more result which will be displayed on the next page....what about them?
    If someone wants the total number of results found on google search then what to do?

    ReplyDelete
  2. http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=android

    By Default it'll show only 4 values.

    If u want more than that you can extend tis upto 8 results by.

    http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=android&rsz=8

    ReplyDelete
  3. result is not shown if i search "android" it doesn't show relevant data about android

    ReplyDelete