Android Dynamic Autocomplete Using Wikipedia Suggest API

This entry was posted on Thursday, February 23rd, 2012 and is filed under Android, apps, JSON.

Autocomplete is one of the important aspect of an application. Majority of the android autocomplete implementation are static, that is autocomplete value is hard-coded in the application. This tutorial makes use of Wikipedia API to implement dynamic Autocomplete.
To know more about JSON click here.

Create a new Project and give Internet permission

<uses-permission android:name="android.permission.INTERNET"/>

Now Create a Main Layout main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         >

        <requestFocus />
    </AutoCompleteTextView>

</LinearLayout>

Now we need to specify the layout for dropdown menu. Name this as item.xml.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp"
    android:textColor="#000"
    android:background="#eaeaea">
</TextView>

We need to make sure that parsing of JSON and HTTP request must be done in separate thread. This will enable a good user interface

Java File

package com.firstamong.wiki;

import java.util.ArrayList;
import java.util.List;

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.json.JSONArray;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class WikiSuggestActivity extends Activity {
	public String data;
	public List<String> suggest;
	public AutoCompleteTextView autoComplete;
    public ArrayAdapter<String> aAdapter;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        suggest = new ArrayList<String>();
        autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
        autoComplete.addTextChangedListener(new TextWatcher(){

			public void afterTextChanged(Editable editable) {
				// TODO Auto-generated method stub
				
			}

			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub
				
			}

			public void onTextChanged(CharSequence s, int start, int before, int count) {
				String newText = s.toString();
				new getJson().execute(newText);
			}
        	
        });
		
    }
   class getJson extends AsyncTask<String,String,String>{

	@Override
	protected String doInBackground(String... key) {
		String newText = key[0];
		newText = newText.trim();
		newText = newText.replace(" ", "+");
		try{
			HttpClient hClient = new DefaultHttpClient();
			HttpGet hGet = new HttpGet("http://en.wikipedia.org/w/api.php?action=opensearch&search="+newText+"&limit=8&namespace=0&format=json");
			ResponseHandler<String> rHandler = new BasicResponseHandler();
			data = hClient.execute(hGet,rHandler);
			suggest = new ArrayList<String>();
			JSONArray jArray = new JSONArray(data);
			for(int i=0;i<jArray.getJSONArray(1).length();i++){
			String SuggestKey = jArray.getJSONArray(1).getString(i);
			suggest.add(SuggestKey);
			}
			
		}catch(Exception e){
			Log.w("Error", e.getMessage());
		}
		runOnUiThread(new Runnable(){
			public void run(){
				 aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);
		         autoComplete.setAdapter(aAdapter);
				 aAdapter.notifyDataSetChanged();
			}
		});
		
		return null;
	}
	   
   }
}

Hope it helps!. Thank You :)

You Might Also Like

Filed Under: Android, apps, JSON

  • Bobo

    Awesome!

  • Newbie

    can you give an tutorial or example like this but instead of wiki I’m going to use my own web server for my autocomplete search ? what is the php codes ? tnx