0

Is it bad practice to pass a UI element, such as a TextView, to AsyncTask.doInBackground() (through AsyncTask.execute()) and to read fields from the view in the background thread? (I know it's not okay to alter GUI elements from a background thread.)

Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101

1 Answers1

3

It is not great, for the simple reason that you do not know if that widget is any good anymore.

Suppose the following happens:

  • You execute the AsyncTask, but it is stuck behind other tasks and does not run right away
  • The user rotates the screen, or presses BACK, or otherwise destroys the activity
  • Your AsyncTask finally starts running and you try accessing this widget

In the best-case scenario, the widget is simply wrong. In the worst-case scenario, whatever you call on it causes some sort of crash, because the hosting activity is destroyed.

AsyncTask itself is fairly obsolete; modern Android development uses other things (LiveData, RxJava, and Kotlin coroutines being the biggest candidates). However, if you wish to use AsyncTask, please ensure that it does not try referencing the activity or its widgets from doInBackground().

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491