我正在尝试提高移动应用的性能。我正在尝试使用AsyncTask。我已经查看了很多关于AsyncTask的文档,同时在这里查看了很多问题,但似乎无法让我的代码正常运行。
我见过在onPostExecute方法中设置适配器的示例,但这对我不起作用..
@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);
}
}
}
由于
答案 0 :(得分:1)
在您的MainActivity中定义RecycleView
,而不是onPreExecute
的{{1}}方法。
使用AsyncTask
方法,您可以设置onCreate
。
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();
}
方法中有UserTimeline
和TweetTimelineRecyclerViewAdapter
(与UI不在同一个线程中),因此无法在doInBackground
中设置适配器。在UI线程上设置适配器。
doInBackground
然后@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;
}
应为空。