[英]I need data from a database access in a different thread for my recyclerview, but then I get “No adapter attached”
I want to populate my RecyclerView, which from what I've heard, needs to be done in the main thread (?).我想填充我的 RecyclerView,据我所知,这需要在主线程(?)中完成。 But I want to populate said RecyclerView with info from my Room, which said query cannot be done in the main thread.
但我想用来自我房间的信息填充所说的 RecyclerView,其中所说的查询不能在主线程中完成。 How do I get around this?
我该如何解决这个问题? I've already tried running all ui related actions in a runOnUiThread():
我已经尝试在 runOnUiThread() 中运行所有与 ui 相关的操作:
public void updateTeams(){
new Thread(new Runnable() {
public void run() {
AppDatabase db = AppDatabase.getInstance(getApplicationContext());
final List<Team> allTeams = db.teamDao().getAll();
runOnUiThread(new Runnable() {
@Override
public void run() {
RecyclerView recyclerView = findViewById(R.id.teamRecyclerView);
TeamRecyclerViewAdapter adapter = new TeamRecyclerViewAdapter(TeamsActivity.this, allTeams);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(TeamsActivity.this));
}
});
}
}).start();
}
I get E/RecyclerView: No adapter attached; skipping layout
我得到
E/RecyclerView: No adapter attached; skipping layout
E/RecyclerView: No adapter attached; skipping layout
and an unpopulated recyclerview E/RecyclerView: No adapter attached; skipping layout
和未填充的回收视图
updateTeams() is called in the onCreate() of the activity. updateTeams() 在活动的 onCreate() 中被调用。 It is also called in onActivityResult() in the same activity.
它也在同一活动中的 onActivityResult() 中调用。 Does that make a difference?
这有什么区别吗?
Try to initialize your RecyclerView and Adapter inside onCreate
like below:尝试在
onCreate
中初始化 RecyclerView 和 Adapter,如下所示:
private RecyclerView recyclerView;
private TeamRecyclerViewAdapter adapter;
private List<Team> allTeams;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
allTeams = new ArrayList<>();
RecyclerView recyclerView = findViewById(R.id.teamRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
TeamRecyclerViewAdapter adapter = new TeamRecyclerViewAdapter(this, allTeams);
recyclerView.setAdapter(adapter);
...
}
And inside runnable just update the data list and notify the adapter like below:在 runnable 中,只需更新数据列表并通知适配器,如下所示:
public void run() {
AppDatabase db = AppDatabase.getInstance(getApplicationContext());
allTeams = db.teamDao().getAll();
runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.