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;
}
}