After answering this question, I got a doubt about the sense/usefulness of using the get() method of Android\'s AsyncTask class.
public final Result get ()
You can use it in your AutoCompleteTextView's adapter's filter.
private class Adapter extends BaseAdapter implements Filterable{
getFilter(){
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<String> suggestions = MyApiSuggestionsApi(constraint).get();
return packageAsFilterResults(suggestions);
}
}
}
The get
method should never be used in the UI thread because it will (as you noticed) freeze your UI. It should be used in a background thread to wait for the end of your task, but generally speaking, try to avoid AsyncTask
as much as possible (WHY?).
I would suggest a callback or eventbus as a replacement.
It appears as though AsyncTask.get() blocks the caller thread, where AsyncTask.execute() does not.
You might want to use AsyncTask.get() for test cases where you want to test a particular Web Service call, but you do not need it to be asynchronous and you would like to control how long it takes to complete. Or any time you would like to test against your web service in a test suite.
Syntax is the same as execute:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
new DownloadFilesTask().get(5000, TimeUnit.MILLISECONDS);