I have a simple android application which has a menu on its action bar. When the item is selected I call a function startStreaming()
. Inside that function I set twitter status listener, so whenever a new tweet comes, I change the graphical interface. Well the program works somehow, but I get some warning like:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
And that's because I am changing the gui in the wrong thread. I tried using AsyncTask
where all job was done in onPostExecute
but I get again the same warning.
Since I would need some delay, meaning that I will change gui each 3 seconds, I thought I could use a separate Thread
and its method runOnUiThread
so I could use Thread.sleep(3000)
. That could also fix my warning.
I would like to get some help to place and modify the content of startStreaming()
in a thread.
public class SearchTwitter extends Activity {
private List<ExampleViewModel> viewModels;
private ExampleViewModel myRow;
private ExampleAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.stream_tag:
startStreaming();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void startStreaming(){
TwitterStream twitterstream = new TwitterStreamFactory().getInstance();
twitter4j.StatusListener listener = new twitter4j.StatusListener() {
@Override
public void onStatus(twitter4j.Status status) { //new posts arrives
if(viewModels.size() > 1){
adapter.viewmodels().remove(viewModels.size() - 1);
String tweetText = status.getText();
myRow = new ExampleViewModel(tweetText);
viewModels.add(myRow);
adapter.notifyDataSetChanged(); // update UI
}
}
};
FilterQuery filterQuery = new FilterQuery();
String[] query = {"#WorldCup2014"};
filterQuery.track(query);
twitterstream.addListener(listener);
twitterstream.filter(filterQuery);
}
}