I have an Android fragment which requests a web page using an AsyncTask and retrieves the page title which should be displayed in a TextView. I invoke the AsyncTask in onCreateView().
The problem is there is a noticiable delay before the AsyncTask completes and the fragment view is created and displayed. It doesn't seem to be running asynchronously.
The code is as follows:
GetWebsiteAsyncTask getWebsiteAsyncTask = new GetWebsiteAsyncTask();
String websiteTitle = getWebsiteAsyncTask.execute().get();
websiteViewModel.setTitle(websiteTitle);
With the AsyncTask defined as:
class GetWebsiteAsyncTask extends AsyncTask<Void, Void, String> {
private static final String TAG = GetWebsiteAsyncTask.class.getName();
@Override
protected String doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect("https://www.google.com").get();
return doc.title();
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
return null;
}
}
Following Selvin's advice in the comment I have modified the code to use a callback delegate in the AsyncTask as follows:
1.
public interface AsyncResponse {
void processFinish(String output);
}
class GetWebsiteAsyncTask extends AsyncTask<Void, Void, String> {
public AsyncResponse delegate = null;
@Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
}
public class WebsiteFragment extends Fragment implements AsyncResponse
GetWebsiteAsyncTask getWebsiteAsyncTask = new GetWebsiteAsyncTask();
getWebsiteAsyncTask.delegate = this;
getWebsiteAsyncTask.execute();
@Override
public void processFinish(String output) {
websiteViewModel.setTitle(output);
}