Reputation: 91
I'm trying to improve the performance of my mobile App. I'm attempting to use AsyncTask. I've looked at quite a lot of documentation on AsyncTask, also looked at numerous questions on here, but can't seem to get my code to run correctly.
I've seen examples where the Adapter is set in the onPostExecute method, but that does not work for me..
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_travel_updates);
Twitter.initialize(this);
new getTweets().execute();
}
private class getTweets extends AsyncTask<Void, Void, Void>{
@Override
protected void onPreExecute() {
super.onPreExecute();
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(travel_updates.this));
}
@Override
protected Void doInBackground(Void... params) {
final UserTimeline searchTimeline = new UserTimeline.Builder().screenName("TflTravelAlerts")
.maxItemsPerRequest(5)
.build();
final TweetTimelineRecyclerViewAdapter tweetAdapter =
new TweetTimelineRecyclerViewAdapter.Builder(travel_updates.this)
.setTimeline(searchTimeline)
.setViewStyle(R.style.tw__TweetLightWithActionsStyle)
.build();
return null;
}
@Override
protected void onPostExecute(Void Void) {
recyclerView.setAdapter(tweetAdapter);
}
}
}
Thanks
Upvotes: 1
Views: 1657
Reputation: 4848
Define your RecycleView
in your MainActivity not in the onPreExecute
method of your AsyncTask
.
With in your onCreate
method you can set the RecyclerView
.
private RecyclerView recyclerView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_travel_updates);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(travel_updates.this));
Twitter.initialize(this);
new getTweets().execute();
}
Because you have UserTimeline
and TweetTimelineRecyclerViewAdapter
inside the doInBackground
method (which is not on the same Thread as you UI) you cannot set the adapter in doInBackground
. Set the adapter on the UI thread.
@Override
protected Void doInBackground(Void... params) {
final UserTimeline searchTimeline = new UserTimeline.Builder().screenName("TflTravelAlerts")
.maxItemsPerRequest(5)
.build();
final TweetTimelineRecyclerViewAdapter tweetAdapter =
new TweetTimelineRecyclerViewAdapter.Builder(travel_updates.this)
.setTimeline(searchTimeline)
.setViewStyle(R.style.tw__TweetLightWithActionsStyle)
.build();
runOnUiThread(new Runnable() {
@Override
public void run() {
recyclerView.setAdapter(tweetAdapter);
});
// I don't think you need to return anything if your method uses void??
return null;
}
Then onPostExecute
should be empty.
Upvotes: 1