Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How can I pass parameters to AsyncTask's onPreExecute()?

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?

like image 985
Steven Meliopoulos Avatar asked Jun 19 '10 09:06

Steven Meliopoulos


People also ask

How to AsyncTask in Android?

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.

Why AsyncTask is deprecated in Android?

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.

What are the parameters in AsyncTask?

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.

How to cancel AsyncTask in Android?

AsynTaskExample mAsyncTask = new AsyncTaskExample(); mAsyncTask. cancel(true);


1 Answers

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(); 
like image 156
Felix Avatar answered Sep 25 '22 06:09

Felix