views:

380

answers:

2

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?

+1  A: 

Creating the member field in your subclass is the way to go.

Elegant doesn't mean this time you have to change how base classes define methods.

Pentium10
Yes, just pass the parameters `onPreExecute()` needs in the constructor for your `AsyncTask`. Frankly, I've never found much of a use for `onPreExecute()`...
CommonsWare
+2  A: 

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();
Felix
This is quite exactly what I did now. I still need a member variable but in the AsyncTask and not the outer class if that's what you mean. This is what I did:private class MyAsyncTask extends AsyncTask<Void, Void, Void> { private boolean showLoading; public MyAsyncTask(boolean showLoading) { super(); this.showLoading = showLoading; // do stuff } protected void onPreExecute(){ if(showLoading){ // ... } } // doInBackground() et al.}
legr3c
Yup, that was pretty much the idea :)
Felix