我试图用片段活动中的Firebase实时数据库中的数据填充FirebaseRecyclerView。问题是当我在设备上编译并运行代码时,没有Visual RecyclerView。通过在线查看RecyclerView的Firebase实现的其他示例,我的代码看起来应该可以工作,但无法理解原因。
PostFragment.java
public class NotificationsFragment extends Fragment {
private NotificationsViewModel notificationsViewModel;
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private DatabaseReference userDBRef = FirebaseDatabase.getInstance().getReference();
private RecyclerView recyclerView;
private FirebaseRecyclerAdapter<Post, PostHolder> firebaseRecyclerAdapter;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
notificationsViewModel =
ViewModelProviders.of(this).get(NotificationsViewModel.class);
View root = inflater.inflate(R.layout.fragment_notifications, container, false)
recyclerView = root.findViewById(R.id.item_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
Query postQuery = userDBRef.child(mAuth.getCurrentUser().getUid()).child("posts");
mDatabase = FirebaseDatabase.getInstance().getReference().child("posts");
FirebaseRecyclerOptions<Post> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(postQuery, Post.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Post, PostHolder>(firebaseRecyclerOptions) {
@Override
protected void onBindViewHolder(@NonNull PostHolder postHolder, int position, @NonNull Post post) {
TextView titleTv = postHolder.titleTextView;
titleTv.setText(post.getPostTitle());
// postHolder.titleTextView.setText(post.getPostTitle());
//postHolder.setPost(post);
}
@Override
public PostHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
PostHolder myPostHolder = new PostHolder(view);
return myPostHolder;
}
};
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(firebaseRecyclerAdapter);
return root;
}
@Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
@Override
public void onStop() {
super.onStop();
if (firebaseRecyclerAdapter!= null) {
firebaseRecyclerAdapter.stopListening();
}
}
private class PostHolder extends RecyclerView.ViewHolder {
private TextView titleTextView, descTextView;
PostHolder(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.row_item);
descTextView = itemView.findViewById(R.id.postdesc);
}
void setPost(Post userPost) {
String postTitle = userPost.getPostTitle();
titleTextView.setText(postTitle);
String desc = userPost.getDescription();
descTextView.setText(desc);
}
}
}