Android:采用Google Suggest API 实现 AutoCompleteTextView的填充

      Android提供了两个令人兴奋的控件:AutoCompleteTextViewMultiAutoCompleteTextView,想了解它们的区别可以参考这里。但是在网上看了很多教程,其填充的内容都是有限的,基本都是写死在程序里。当我们在Google搜索框输入一些文字时,Google会提示相关的热门搜索词条,把这些词条填充到AutoCompleteTextView中将会是一件很棒的事情。这里就分享下如何从Google 的Suggest API获取实时Suggest,当然了也可以在自己的服务器上提供相应的API来实现特定的需求。

1、Google Suggest API 介绍:

      URL:http://google.com/complete/search?output=toolbar&q=关键字&hl=国家

     ( 其中的hl参数: 中国:zh-CN

                                   日本:ja

                                   不带该参数的话,默认是英语语系)

       返回的XML格式很简单,比较容易解析:(下面为该xml的解析工具类)

     

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

import android.util.Log;

public class GoogleSuggestionAPI {

	public static List<String> getSuggestion(String text)
			throws ClientProtocolException, IOException, Exception {
		List<String> result = new ArrayList<String>();

		//
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		try {

			HttpClient httpget = new DefaultHttpClient();
			HttpGet request = new HttpGet(
					"http://google.com/complete/search?output=toolbar&q="
							+ URLEncoder.encode(text).replace("%EF%BB%BF", "")
							+ "&hl=ja");

			request.setHeader("charset", "utf-8");

			ResponseHandler<String> rh = new BasicResponseHandler();
			String response = httpget.execute(request, rh);

			InputStream is = new ByteArrayInputStream(
					response.getBytes("UTF-8"));

			DocumentBuilder builder = factory.newDocumentBuilder();
			Document dom;
			dom = builder.parse(is);

			org.w3c.dom.Element root = dom.getDocumentElement();
			// Log.e("XML", root.toString());
			NodeList items = root.getElementsByTagName("suggestion");

			for (int i = 0; i < items.getLength(); i++) {
				Element element = (Element) items.item(i);
				result.add(element.getAttribute("data").toString());
//				Log.e("encode", element.getAttribute("data").toString());

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@SuppressWarnings("unused")
	private static String convertStreamToString(InputStream is) {


		Charset ch = Charset.forName("UTF8");
		Log.i("ccc", "CHARSET=" + ch.displayName());

		BufferedReader reader = new BufferedReader(
				new InputStreamReader(is, ch));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		String originalStr = new String(sb.toString());

		return sb.toString();
	}

	public static Document parse(String xml) {
		Document doc = null;
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			// encode the xml to UTF -8

			ByteArrayInputStream encXML = new ByteArrayInputStream(
					xml.getBytes("UTF8"));

			doc = builder.parse(encXML);
			// Log.e("XML parsing OK");

			return doc;
		} catch (Exception e) {
			// log.error("Parser Error:" + e.getMessage());
			// throw new ParsingFailedException(
			// "Failed to parse XML : Document not well formed", e);
		}
		return doc;
	}

}

2、  实现的思路 

        AutoCompleteTextView具体的用法就不讲了,具体的思路是为AutoCompleteTextView注册TextChangedListener,当Text改变时,启动一个AsyncTask调用上面的工具类,

解析完XML后,更新AutoCompleteTextView的adapter,因为具体的代码混入了很多自己项目的东西,不便于阅读,有需要的可以留言。


3、Yahoo提供的类似API

     http://search.yahooapis.com/WebSearchService/V1/relatedSuggestion?appid=程序ID&query=关键字

    (程序ID需要到这里申请)

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值