Search code examples
androidmultithreadingexceptionstatus

Android CalledFromWrongThreadException


I've seen a lot of questions about this subject but i'm really not happy with any answer.

What i want its to have a class ConnectionController implements Runnable that is responsible for opening the conection to server, read and write messages to it and have to be instantiated since the beginning of the application through the end.

I have a class MainActivity extends from Activity that onCreate it will instantiate a ConnectionController object.

That connectionController has to change some fields on MainActivity (and eventually in another activities), like status conections ImageView for example, or even received messages TextView.

Because connectionController is a Thread i cannot access to elements (CalledFromWrongThreadException (Only the original thread that created a view hierarchy can touch its views).

What do you recommend to use? I saw solution with async tasks, handlers, myUIRunnable but i didn't understand what is the best solution for this situation.

Thanks in advance.


Solution

  • That connectionController has to change some fields on MainActivity (and eventually in another activities), like status conections ImageView for example, or even received messages TextView.

    No, it does not. It needs to arrange for those things to be changed. Since you elected to make a "controller" be a thread for some reason, the controller cannot change those UI elements itself.

    What do you recommend to use?

    Use post() on a View. Or, use runOnUiThread() on an Activity. Or, use a Handler.