Skip to content Skip to sidebar Skip to footer

Altering Ui Thread's Views In Asynctask In Doinbackground, Calledfromwrongthreadexception Not Always Thrown

The following code in an AsycnTask: @Override protected Boolean doInBackground(View... params) { try{ Drawable drawPhoto = DataDatero.ImageDownload(taskPhotoName); ((Imag

Solution 1:

I have come across a similar issue and asked a question here (self answered after a good bit of digging).

Essentially what it boils down to is that, contrary to what everybody thinks, you can modify UI elements from an AsyncTaskexecute()if those views haven't gone through a layout traversal yet. This happens asynchronously to the main flow of execution (activity lifecycle methods/callbacks), so if the View in question is created shortly before execute() is called, you can access them (meaning, the exception isn't thrown, it's of course still really bad practice and not advisable). Because execute() happens on another thread, the layout traversals (which run on the UI thread) may finish while your execute() is running, which explains why only some views may be modified and others throw the exception. It also explains why "leaving only the textview updates" (and presumably removing the ImageView updates) results in those updates "magically" working too. Since this is a timing related issue, it depends on many factors, among other things how long Drawable drawPhoto = DataDatero.ImageDownload(taskPhotoName); takes to run.

PS: I realise this is a late answer, but I think this can be useful for somebody finding this answer first, there aren't many posts dealing with issues like this.

Solution 2:

The exception is clear enough. You can not update UI element from a thread different from the UI Thread. doInBackground executes code in a different thread

Solution 3:

Why cant you pass the information to update the UI to the onPostExecute method? This is where the UI is intended to be updated.

Solution 4:

When you run the execute method of your task, the doInBackground method is executed in a background thread.

And you are not allowed to modify UI from a background thread.

So, don't modify the UI in the doInBackground method.

You should do this UI stuff in onPostExecute method instead, which is guaranteed to be executed in UI thread.

Post a Comment for "Altering Ui Thread's Views In Asynctask In Doinbackground, Calledfromwrongthreadexception Not Always Thrown"