Reputation: 26441
I'm using Twitter4j in asynchronous mode. When I get response in Listener I want to be able to change some Views in my Activity but it results in CalledFromWrongThreadException
.
I know that I can use runOnUiThread
method, but what is the most elegant solution for this apart from inlining Runnable Classes?
Part of my Activity:
TwitterListener listener = new TwitterAdapter() {
@Override
public void gotUserDetail(User user) {
super.gotUserDetail(user);
fillInUserProfileDetails(user);
Upvotes: 3
Views: 1645
Reputation: 1699
I don't think there is any more "elegant" solution than Activity.runOnUiThread(Runnable)
or View.post(Runnable)
. You've probably already seen the discussion of threading in the Android docs:
EDIT: http://android-developers.blogspot.com/2009/05/painless-threading.html
As stated there, the Android UI toolkit is not threadsafe, so all interaction with it must occur on the same thread, namely the application's UI thread; and if you're going to pass work from one thread to another, you will need a Runnable object to encapsulate the work to be performed.
I know that anonymous inner classes can look rather messy, but they are quite a common idiom in Java, since they are the closest thing to closures available in the language. So the best thing for you to do, IMO, is grit your teeth and use Activity.runOnUiThread(Runnable)
, and remind yourself that elegance is in the eye of the programmer.
Upvotes: 3