Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should findviewbyid be called in UI thread?

Tags:

java

android

The question is: should I call Activity.findViewById in the UI thread only?

The reason I'm asking is that I call it from an arbitrary thread and it works flawlessly. But then I got an exception from one of the users: findViewById fails with NPE somewhere in findViewTraversal.

So, can it be the cause?

like image 605
Andy Avatar asked Jul 02 '11 10:07

Andy


1 Answers

the Android UI toolkit is not thread-safe and must always be manipulated on the UI thread.

Taken from Painless threading.

Because it's not thread-safe, you don't know what will happen if you use the API in another thread. It might work, it might not work, it might work most of the time, might never work or it might work and breaks other things. You can't tell.

Thus, if you want a correct application, you must do this in the UI thread.

like image 139
Ishtar Avatar answered Oct 02 '22 22:10

Ishtar