I use an AsyncTask
for loading operations that I implemented as an inner class.
In onPreExecute()
I show a loading dialog which I then hide again in onPostExecute()
. But for some of the loading operations I know in advance that they will finish very quickly so I don't want to display the loading dialog.
I wanted to indicate this by a boolean parameter that I could pass to onPreExecute()
but apparently for some reason onPreExecute()
doesn't take any parameters.
The obvious workaround would probably be to create a member field in my AsyncTask or in the outer class which I would have to set before every loading operation but that does not seem very elegant. Is there a better way to do this?
To start an AsyncTask the following snippet must be present in the MainActivity class : MyTask myTask = new MyTask(); myTask. execute(); In the above snippet we've used a sample classname that extends AsyncTask and execute method is used to start the background thread.
This class was deprecated in API level 30.AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.
Google's Android Documentation Says that : An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
AsynTaskExample mAsyncTask = new AsyncTaskExample(); mAsyncTask. cancel(true);
You can override the constructor. Something like:
private class MyAsyncTask extends AsyncTask<Void, Void, Void> { public MyAsyncTask(boolean showLoading) { super(); // do stuff } // doInBackground() et al. }
Then, when calling the task, do something like:
new MyAsyncTask(true).execute(maybe_other_params);
Edit: this is more useful than creating member variables because it simplifies the task invocation. Compare the code above with:
MyAsyncTask task = new MyAsyncTask(); task.showLoading = false; task.execute();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With