我正在为我的应用程序使用Firebase数据库。我可以从数据库中添加和检索数据,但是当我尝试在阵列列表中添加检索到的数据时,无法填充阵列列表。
public void retrievePosts(){
retrievePosts.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast toast = Toast.makeText(getApplicationContext(), "There are " + dataSnapshot.getChildrenCount() + " blog posts", Toast.LENGTH_LONG);
toast.show();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Post post = postSnapshot.getValue(Post.class);
//adding data to the list
Toast toastNew = Toast.makeText(getApplicationContext(), post.getAuthor()+"_"+post.getTitle()+"_"+post.getContent(), Toast.LENGTH_SHORT);
toastNew.show();
postList.add(post);
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
Snackbar snackbar = Snackbar.make(coordinatorLayout, "Unable to fetch posts", Snackbar.LENGTH_LONG);
snackbar.show();
}
});
}
这个retrievePosts方法正在解析我的数据,以及postList.add(post);。我正在尝试将数据添加到arraylist中。在调用retrievePosts()之前,我已经初始化了arraylist。方法,然后尝试在我的recyclyerView中添加arraylist
postList = new ArrayList<Post>();
retrievePosts();
fab= (com.melnykov.fab.FloatingActionButton) findViewById(R.id.fab);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(postList);
mRecyclerView.setAdapter(mAdapter);
找不到我在做什么错。提前致谢!
如果您的适配器引用了postList
,则还需要在postList
更改时告知它,以便它可以告诉RecyclerView它需要重新查询它(适配器)以获取更新的视图。
你可以用做此notifyDataSetChanged()
方法的RecyclerView.Adapter
。
您应该警惕-尽管不太可能,但是可能会在初始化适配器之前检索帖子(如果您使用上面的答案,则会导致空指针异常)。我会将retrievePosts()
通话移到最后。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句