sandalone
sandalone

Reputation: 41759

Is it bad practice to have two AsyncTask inner classes in one file?

In one Activity, I have 2 heavy tasks. One is a creation of the default database with default rows and values. The other one is fetching all data from the database to populate UI elements on the screen. There are over 100 UI elements on that page (statistical data).

Now, would it be bad to have two AsyncTask classes in one Java code file? One would be used to create default database (activated only on first start) and the other one would be used a lot of times to fetch all data from the database needed to populate the afore mentioned UI elements.

I am asking about bad practice and not about the fact whether the same AsyncTask class could be used for both heavy tasks (via if/else).

Upvotes: 3

Views: 1034

Answers (3)

Praful Bhatnagar
Praful Bhatnagar

Reputation: 7435

I think It is ok to have more then one AsyncTask In on activity if they perform totally different task.

Upvotes: 1

ngesh
ngesh

Reputation: 13501

A better way is Take out the AsyncTask and create a public class wihich has 2 methods 1 for fetching and one for creating database..

This really has the Advantage of OO and also it reduces your code and seperates UI from BackgroundTask...

Upvotes: 1

Saad Farooq
Saad Farooq

Reputation: 13402

Nope. Don't think so. How else would you do two background tasks ?

I would recommend however that for code clarity you use a design pattern whereby the result of the background tasks is differentiated in the same method using request codes that you send to the AsyncTask.

Something like:

new AsyncTask1(this, 0).execute();
new AsyncTask2(this, 1).execute();

The AsyncTask can then call back the same method in the Activity and you can differentiate on the basis of the request code.

onBackgroundTaskCompleted(int requestCode, Object result) {
    if (requestCode == 0 ) {
        // do something
    } else {
        // do something else
    }

For an example of using this pattern using interface have a look at the async classes at : https://github.com/sfarooq/A-droid-lib/

Upvotes: 2

Related Questions