我正在尝试创建一个可搜索的活动,该活动从 google 地方 API 获取其结果,我创建了一个内容提供程序并放置了一些代码来执行对 google 的 HTTP 请求并解析结果。
问题是 Web 请求需要异步完成以阻止它阻塞 UI 线程,当它这样做时,内容提供者在 Web 请求完成之前返回 MatrixCursor 使结果在下一次文本框更改时出现文本实际更改的时间。
有没有办法解决?
这是我的搜索内容提供商的代码:
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;
}
}