Java – Android: Can you access AsyncTask class members in DoInBackground?

Android: Can you access AsyncTask class members in DoInBackground?… here is a solution to the problem.

Android: Can you access AsyncTask class members in DoInBackground?

Is it safe to run methods of AsyncTask class members in DoInBackground? Or do you need to use a handler?

private class MyAsyncTask extends AsyncTask<Void, Void, Void> {

Object mObjA = null:

private MyAsyncTask(Object objA) {
        mObjA = objA
    }

protected void doInBackground(Void... params) {
        mObjA.aMethod()
    }

}

If mObjA is

not passed as a parameter, is it safe to run mObjA.aMethod() in doInBackground? Is there a multithreading issue?

Should you only access objects that are passed intentionally in doInBackground, or can you freely access any member of the class without using a handler?

Solution

You can indeed access any field of your AsyncTask in doInBackground(), provided that mObjA is not UI-related and Android is basically like ViewPager or LinearLayout or any type of ViewGroup class.

Related Problems and Solutions