如何在Firebase中获取自动递增子节点名及produit子项并展示到RecyclerView
实现步骤
1. 读取Firebase中produit节点数据
先创建商品实体类,用于存储对应节点的键(商品名)、值(商品数量):
public class Product { private String productName; private int quantity; // 空构造方法为Firebase反射必需 public Product() {} public Product(String productName, int quantity) { this.productName = productName; this.quantity = quantity; } // 自行补充对应字段的getter、setter方法 }
在需要加载数据的页面添加Firebase数据监听:
// 替换为你业务中对应produit节点的引用 DatabaseReference produitRef = reference.child(refernce).child("produit"); List<Product> productList = new ArrayList<>(); produitRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { productList.clear(); // 遍历produit下所有子节点 for (DataSnapshot childSnapshot : snapshot.getChildren()) { String productName = childSnapshot.getKey(); Integer quantity = childSnapshot.getValue(Integer.class); if (productName != null && quantity != null) { productList.add(new Product(productName, quantity)); } } // 数据加载完成后通知适配器刷新 productAdapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError error) { // 自行补充读取错误的处理逻辑 Log.e("FirebaseRead", "读取失败: " + error.getMessage()); } });
2. 适配RecyclerView展示数据
首先自行创建RecyclerView单条目的布局文件,示例适配器代码如下:
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> { private List<Product> productList; public ProductAdapter(List<Product> productList) { this.productList = productList; } @NonNull @Override public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_product, parent, false); return new ProductViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull ProductViewHolder holder, int position) { Product product = productList.get(position); holder.tvProductName.setText(product.getProductName()); holder.tvQuantity.setText("数量:" + product.getQuantity()); } @Override public int getItemCount() { return productList.size(); } public static class ProductViewHolder extends RecyclerView.ViewHolder { TextView tvProductName, tvQuantity; public ProductViewHolder(@NonNull View itemView) { super(itemView); // 替换为你自己条目布局里的对应控件ID tvProductName = itemView.findViewById(R.id.tv_product_name); tvQuantity = itemView.findViewById(R.id.tv_quantity); } } }
初始化RecyclerView示例:
RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); ProductAdapter productAdapter = new ProductAdapter(productList); recyclerView.setAdapter(productAdapter);
内容的提问来源于stack exchange,提问作者Mohamed Yacine Zouaoui
相关产品推荐
相关产品推荐

