使用RadioButtons实现Firebase用户主页帖子按餐食筛选功能异常咨询
原功能实现效果参考:

修复方案
已知问题清单
- 条件判断误用位运算符
&,需改为逻辑与&&,原有写法会导致条件判断逻辑不符合预期 - 每次筛选前未清空
postList,历史缓存数据和新筛选结果叠加,导致页面始终展示全部帖子 - 仅绑定了「早餐」单选按钮的选中判断,其余餐食选项选中后不会触发对应筛选逻辑
- 未对
Meal字段做判空处理,极端情况会触发空指针导致逻辑中断 - 使用
addValueEventListener持续监听数据库,重复点击筛选会触发多次回调,建议替换为单次查询
修正后代码
// 先获取RadioGroup而不是单个RadioButton final RadioGroup mealRadioGroup = bottomSheetView.findViewById(R.id.your_radio_group_id); // 替换为你布局里RadioGroup的实际ID bottomSheetView.findViewById(R.id.btnFilter).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int checkedId = mealRadioGroup.getCheckedRadioButtonId(); // 没有选中任何选项时可以自行处理,比如展示全部帖子 if(checkedId == -1) { // 这里补充展示全部帖子的逻辑即可 return; } RadioButton checkedBtn = bottomSheetView.findViewById(checkedId); String targetMeal = checkedBtn.getText().toString(); DatabaseReference reference = FirebaseDatabase.getInstance().getReference("posts"); // 用单次查询替代持续监听 reference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { // 筛选前先清空原有列表 postList.clear(); for (DataSnapshot snapshot : dataSnapshot.getChildren()) { Post post = snapshot.getValue(Post.class); // 先判空,再用&&做逻辑与判断 if(post != null && post.getPublisher().equals(profileid) && snapshot.child("Meal").getValue() != null && snapshot.child("Meal").getValue().toString().equals(targetMeal)) { if (snapshot.child("ingrediant").getValue() != null){ ArrayList<String> mList = new ArrayList<>(); for (DataSnapshot ds:snapshot.child("ingrediant").getChildren()){ mList.add(ds.getKey()+":"+ds.getValue()); } post.setIngrediantsList(mList); } post.setVideo((Boolean) snapshot.child("isVideo").getValue()); postList.add(post); } } Collections.reverse(postList); myFotosAdapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { // 建议添加异常处理逻辑 } }); } });
额外注意事项
- 请将代码中的
your_radio_group_id替换为你布局文件中包裹所有RadioButton的RadioGroup组件的实际ID - 如果需要实现选中空选项时展示全部帖子,在
checkedId == -1的分支中补充查询全部对应用户帖子的逻辑即可
内容的提问来源于stack exchange,提问作者SSS
相关产品推荐
相关产品推荐

