I have seen this answer: How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
But it is not what I am asking since my calling class has multiple calls to the AsyncTask
.
I want to create a generic AsyncTask
class which will accept the URL and download content from the given URL and return the downloaded content.
Example:
public class MyAsyncTask extends AsyncTask<String, Void, String>{
ProgressDialog dialog;
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(context, "Loading", "Please wait...", true);
}
protected String doInBackground(String... params) {
// do download here
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
dialog.dismiss();
}
}
And I have another class which calls this AsyncTask
in different scenarios
public class MyClass {
public method1(String url) {
String result = new MyAsyncTask().execute(url).get();
}
public method2(String url) {
String result = new MyAsyncTask().execute(url).get();
}
}
I know that using get()
method will make this entire process a sync task. But I want to get the result back to calling class. And I also know, to prevent it, I have to implement an interface. But since I have multiple calls in the same class it is not possible. So can anyone give me an idea to solve this?