Reputation: 531
I working on implementation of autocomplete suggestion via some REST API (it's actually Nokia Here Geocoder Autocomplete API, but its not so important). I write custom adapter for AutoCompleteTextView
.
public class GeoAutocompleteAdapter extends BaseAdapter implements Filterable {
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected Filter.FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
// obtain some autocomplete data
filterResults.values = res;
filterResults.count = res.size();
return filterResults;
}
//...
}
//...
}
As far as I understand, section "obtain some autocomplete data"
run in thread pool. If I obtain results for autocomplete in synchronous way - its working. For example, I can use HttpURLConnection
and InputStream
- all synchronous blocking call works pretty well here.
But what if I need to call some API here, which operate in asynchronous way, like via Callback \ Listener?
How can I call something like this inside performFiltering ?
request.execute(
new ResultListener<List<com.here.android.mpa.search.Location>>() {
@Override
public void onCompleted(List<Location> locations, ErrorCode errorCode) {
}
//...
}
How can I postpone returning from methods while callback not give me an results?
Thanks in advance,
Upvotes: 4
Views: 1206
Reputation: 7002
You can make the thread to wait for results from async API in performFiltering method till response is received.
Since method performFiltering runs in a worker thread, you can make the thread wait for results as shown below, lockTwo is object and placeResults boolean indicator.
while (!placeResults) {
synchronized (lockTwo) {
try {
lockTwo.wait();
} catch (InterruptedException e) {
}
}
}
In the callback or listener, once response is processed, add notify as shown below.
placeResults = true;
synchronized (lockTwo) {
lockTwo.notifyAll();
}
For more information you can check places auto search example at http://www.zoftino.com/google-places-auto-complete-android
Upvotes: 6