我正在撰写关于课堂公告的论文,我也陷入了困境。
在我的数据库中,我决定将不同用户的帖子放在几个类别中。
分类
显示帖子的类别
所以我已成功显示一个类别(类通知)下的所有帖子。
课堂公告
private RecyclerView postList;
private DatabaseReference database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addPost = findViewById(R.id.btnAddPost);
database = FirebaseDatabase.getInstance().getReference().child("St Isidore of Seville")
.child("Posts").child("Classroom Announcements");
postList = findViewById(R.id.postList);
postList.setLayoutManager(new LinearLayoutManager(this));
}
@Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Post> options= new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(database, Post.class).build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options) {
@Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_row, parent, false);
return new PostViewHolder(view);
}
@Override
protected void onBindViewHolder(@NonNull PostViewHolder holder, int position, @NonNull Post model) {
holder.setTitle(model.getTitle());
holder.setMessage(model.getMessage());
holder.setDateCreated(model.getDateCreated());
}
};
postList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
问题是只有“课堂公告”下的公告才是唯一可以显示的帖子。如何显示所有公告,例如“Bills”,“Homeworks”,“Others”等下的公告......
我可以使用
之类的东西database = FirebaseDatabase.getInstance().getReference().child("St Isidore of Seville")
.child("Posts");
或尽快将数据库中的每个类别放入一个FirebaseRecyclerAdapter中,以便我可以使用他们的日期显示最新帖子?
答案 0 :(得分:0)
您需要使用getChildren()
两次,因此请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("St Isidore of Seville").child("Posts");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
for(DataSnapshot child : ds.getChildren()) {
Post model = child.getValue(Post.class);
Log.d("TAG", model.getTitle() + " / " + model.getMessage() + " / " + model.getDateCreated());
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
postsRef.addListenerForSingleValueEvent(eventListener);