-1

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;
    }
}
lschmid
  • 183
  • 1
  • 1
  • 11
  • 1
    hint: onPostExecute + check documentation – Selvin Nov 19 '21 at 11:16
  • Ok, I got it working. I guess that was actually obvious I would need a callback on the async method completing. Calling get() must be similar to using .Result on a C# async method. – lschmid Nov 19 '21 at 11:22

1 Answers1

0

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);
}
lschmid
  • 183
  • 1
  • 1
  • 11