0

This post says (in reference to the Android Doc) that any method on a view has to be called from the UI thread. However, I have not ran into any problem yet, though I set the OnClickListeners of Buttons in a non-UI-thread. Is this a situation of "You realy should not do this, even though you can." or is there a subset of methods that can actually be called from non-UI-threads?

If the latter is true, which operations are part of the subset?


EDIT

Example code:

Thread setUpActivity = new Thread(new Runnable() { @Override public void run() { while (serviceConnection.getAppController() == null){ try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } btAddTag.setOnClickListener(onAddTag); btGo.setOnClickListener(onGo); runOnUiThread(new Runnable() { @Override public void run() { setUpSpinner(); } }); } }); setUpActivity.start(); 
1
  • 1
    can you show code where you set the OnClickListeners of Buttons in a non-UI-thread.? Commented Aug 4, 2015 at 8:48

2 Answers 2

0

A quick answer would be: You shouldn't do write operations on UI components from outside of the UI thread. This is because the UI components are not thread safe. And even if you might get away with a minor change on a device or emulator, you might get in trouble on other devices or in different situations.

Write operations would be:

  • set text, sizes, colors, etc.

I guess setting just a click listener won't get you into problems if you are not doing UI updates in the callback method(onClick..). But as a good practice I would advice not to do that(set the click listener on a non UI thread).

Sign up to request clarification or add additional context in comments.

1 Comment

"But as a good practice I would advice not to do <<that>>". By <<that>> you mean you would not set the listener in the non-UI-thread, right?
0

You can set listeners on non UI thread. Even if you really do not want it on non UI thread but on UI thread try using post method on view which will call on UI thread.

Usage :

view.post(new Runnable() { public void run() { // your action here on UI thread. } }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.