Jack
Jack

Reputation: 3799

Android search suggestions from API

I'm trying to create a searchable activity that gets its results from the google places API, I've created a content provider and put some code to do the HTTP request to google and parse the result.

The problem is that the web request needs to be done asynchronously to stop it blocking the UI thread, when it is done like this the content provider returns the MatrixCursor before the web request has completed making the results appear the next time the text box changes instead of when the text actually changes.

Is there any way around this?

Here is my code for my search content provider:


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

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

import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentValues; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.util.Log;

import com.loopj.android.http.*;

public class LocationsSuggestionProvider extends ContentProvider { private static final String[] COLUMNS = { "_id", // must include this column SearchManager.SUGGEST_COLUMN_TEXT_1}; public MatrixCursor cursor = new MatrixCursor(COLUMNS); public LocationsSuggestionProvider() {

}
@Override
public int delete(Uri arg0, String arg1, String[] arg2) {
    return 0;
}

@Override
public String getType(Uri uri) {

    return null;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
    return null;
}

@Override
public boolean onCreate() {
    return false;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    if(selectionArgs[0].length() >= 2 && selectionArgs[0].length() < 75)
    {
        AsyncHttpClient client = new AsyncHttpClient();
        try {
            Log.d("Bustimes","https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ URLEncoder.encode(selectionArgs[0].trim(), "UTF-8") +"&sensor=false&key=AIzaSyCvGtqoDK_SoBWG94CKOjymnOc-dzXr8WA&language=en-GB&components=country:gb");
            client.get("https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ URLEncoder.encode(selectionArgs[0].trim(), "UTF-8") +"&sensor=false&key=AIzaSyCvGtqoDK_SoBWG94CKOjymnOc-dzXr8WA&language=en-GB&components=country:gb", new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(String response) {
                    JSONObject jObject = null;
                    try {
                        jObject = new JSONObject(response);

                        JSONArray predictions = jObject.getJSONArray("predictions");
                        for(int i = 0;i < predictions.length(); i++)
                        {
                            JSONObject prediction = predictions.getJSONObject(i);
                            LocationsSuggestionProvider.this.cursor.addRow(new Object[] {i,prediction.getString("description").toString()});
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    MatrixCursor returnMatrix = cursor;
    cursor = new MatrixCursor(COLUMNS);
    return returnMatrix;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
        String[] selectionArgs) {
    return 0;
}

}

Upvotes: 2

Views: 2586

Answers (1)

Jack
Jack

Reputation: 3799

It turns out that you don't need to do any of this asynchronously because the request to the content provider isn't ran on the UI thread anyway. This means you can just do the web request normally without an async task or whatever you would do and it will work fine.

Upvotes: 6

Related Questions