Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use AsyncTask class inside the MainActivity extending Activity?

I was wondering if AsyncTask was made to be used inside the main activity (MainActivity.java) running the thread.

For example I noticed many tutorials when using the AsyncTask they declare a private class inside the main class extending the Activity rather than creating an independent .java file for that AsyncTask (MyAsyncTask.java) class.

But I noticed that when using an independent file i'm not being able to run the runOnUIThread() because it belongs to the Activity class, so how will i be able to use this method inside that independent AsyncTask (MyAsyncTask.java) which extends AsyncTask and not Activity.

like image 641
Alex Avatar asked Mar 14 '13 12:03

Alex


1 Answers

That is completely fine. I do it often but it depends on how you are using it. If it may be used by othe Activities then I give it it's own class or a shared class. But if it is for a single purpose then I would make it an inner class of the MainActivity.

The benefit of making it an inner class is that it has direct access to that classes member variables. If you make it a separate class then you just need to create a constructor for it if you need to pass in params such as a context or other variables.

I don't know exactly what you are doing but I'm not sure you need runOnUiThread(). You can create a constructor in your AsyncTask file and have it accept context as a param and whatever else you need. Then you can update the UI in onPostExecute()

Example

public class MyAsyncTask extends AsyncTask{

    private Context context; 

    public MyAsyncTask(Context context) {  // can take other params if needed
        this.context = context;
    }

    // Add your AsyncTask methods and logic
    //you can use your context variable in onPostExecute() to manipulate activity UI
}

then call it in your MainActivity

MyAsyncTask myTask = new MyAsyncTask(this);  //can pass other variables as needed
myTask.execute();
like image 155
codeMagic Avatar answered Nov 15 '22 15:11

codeMagic