在 Firebase 实时数据库中,我如何遍历每个产品并在回收站视图中显示它们的详细信息

Posted

技术标签:

【中文标题】在 Firebase 实时数据库中,我如何遍历每个产品并在回收站视图中显示它们的详细信息【英文标题】:In Firebase Real time Database , How can I iterate through each product and display their details in a recycler view 【发布时间】:2020-08-12 17:07:56 【问题描述】:

This is how my database looks

我想像这样遍历所有子节点并从它们各自的子节点中检索值但我无法做到这一点,无论如何请建议这样做。 需要显示列表的片段代码如下

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple @link Fragment subclass.
 * Use the @link HomeFragment#newInstance factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment 
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    RecyclerView recyclerView;
    List<Product> productList;
    public HomeFragment() 
        // Required empty public constructor
    

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) 
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        if (getArguments() != null) 
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        
    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 
        // Inflate the layout for this fragment
        View v=  inflater.inflate(R.layout.fragment_home, container, false);
        recyclerView = v.findViewById(R.id.recyclerView);
        initData();
        initRecyclerView();
        return v;
    

    private void initRecyclerView() 
        ProductAdapter productAdapter = new ProductAdapter(productList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(productAdapter);
    

    private void initData() 
        String user = FirebaseAuth.getInstance().getCurrentUser().getUid();

        productList = new ArrayList<>();
        FirebaseDatabase.getInstance().getReference().child(user)
                .addListenerForSingleValueEvent(new ValueEventListener() 
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) 
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) 

                            String pname = snapshot.child("pname").getValue(String.class);
                            String pdesc = dataSnapshot.child("description").getValue(String.class);
                            String price = dataSnapshot.child("price").getValue(String.class);
                            String imgURL = dataSnapshot.child("image").getValue(String.class);
                            productList.add(new Product(pname,price,pdesc,imgURL));

                        
                    
                    @Override
                    public void onCancelled(DatabaseError databaseError) 
                    
                );

    



产品适配器类的代码如下


import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductVH> 

    private static final String TAG = "ProductAdapter";
    List<Product> productList;

    public ProductAdapter(List<Product> productList) 
        this.productList = productList;
    

    @NonNull
    @Override
    public ProductVH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);
        return new ProductVH(view);
    

    @Override
    public void onBindViewHolder(@NonNull ProductVH holder, int position) 
        Product product = productList.get(position);
        holder.prodName.setText(product.getProductName());
        holder.prodPrice.setText(product.getProductPrice());
        holder.prodDesc.setText(product.getProductDesc());

        boolean isExpanded = productList.get(position).isExpanded();
        holder.expandableLayout.setVisibility(isExpanded ? View.VISIBLE : View.GONE);
    





    @Override
    public int getItemCount() 
        return productList.size();
    

    public class ProductVH extends RecyclerView.ViewHolder 
        private static final String TAG = "ProductVH";
        ConstraintLayout expandableLayout;
        TextView prodName , prodPrice , prodDesc ;
        ImageView productImage , delete , instock , edit;

        public ProductVH(@NonNull View itemView) 
            super(itemView);

            expandableLayout = itemView.findViewById(R.id.expandableLayout);
            prodName = itemView.findViewById(R.id.product_list_name);
            prodPrice = itemView.findViewById(R.id.product_list_price);
            prodDesc = itemView.findViewById(R.id.product_description);
            productImage = itemView.findViewById(R.id.product_image);
            delete = itemView.findViewById(R.id.delete);
            instock = itemView.findViewById(R.id.in_stock);
            edit = itemView.findViewById(R.id.edit);


            prodName.setOnClickListener(new View.OnClickListener() 
                @Override
                public void onClick(View v) 
                    Product product = productList.get(getAdapterPosition());
                    product.setExpanded(!product.isExpanded());
                    notifyItemChanged(getAdapterPosition());
                
            );
        
    

Product 类如下所示


public class Product 
    String productName,productDesc, productPrice,imgURI;
    private boolean expanded;

    public Product() 
    

    public Product(String productName, String productDesc, String productPrice, String imgURI) 
        this.productName = productName;
        this.productDesc = productDesc;
        this.productPrice = productPrice;
        this.imgURI = imgURI;
    



    public String getProductName() 
        return productName;
    

    public void setProductName(String productName) 
        this.productName = productName;
    

    public String getProductDesc() 
        return productDesc;
    

    public void setProductDesc(String productDesc) 
        this.productDesc = productDesc;
    

    public String getProductPrice() 
        return productPrice;
    

    public void setProductPrice(String productPrice) 
        this.productPrice = productPrice;
    

    public String getImgURI() 
        return imgURI;
    

    public void setImgURI(String imgURI) 
        this.imgURI = imgURI;
    

    public boolean isExpanded() 
        return expanded;
    

    public void setExpanded(boolean expanded) 
        this.expanded = expanded;
    

    @Override
    public String toString() 
        return "Movie" +
                "Product name ='" + productName + '\'' +
                ", price ='" + productPrice + '\'' +
                ", product descrition ='" + productDesc + '\'' +
                ", image ='" + imgURI + '\'' +
                ", expanded=" + expanded +
                '';
    

【问题讨论】:

参考这个:***.com/questions/54578292/… 发布错误代码,以便我们为您提供帮助。 @Makdous 我已经发布了我的代码先生 将数据库图像添加到问题中,而不是作为链接。 @HasanBouTaam 我已经添加了数据库图像先生 【参考方案1】:

您的数据读数似乎不错:

移动这一行:

initRecyclerView();

直接在此处的 for 循环之后:

    FirebaseDatabase.getInstance().getReference().child(user)
            .addListenerForSingleValueEvent(new ValueEventListener() 
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) 
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) 

                        String pname = snapshot.child("pname").getValue(String.class);
                        String pdesc = dataSnapshot.child("description").getValue(String.class);
                        String price = dataSnapshot.child("price").getValue(String.class);
                        String imgURL = dataSnapshot.child("image").getValue(String.class);
                        productList.add(new Product(pname,price,pdesc,imgURL));

                    

                //here
                initRecyclerView();
                
                @Override
                public void onCancelled(DatabaseError databaseError) 
                
            );

【讨论】:

当我这样做时应用程序崩溃当我点击主页按钮时。logcat 显示此错误java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.prj.ProductAdapter.onBindViewHolder(ProductAdapter.java:36) at com.example.prj.ProductAdapter.onBindViewHolder(ProductAdapter.java:15)

以上是关于在 Firebase 实时数据库中,我如何遍历每个产品并在回收站视图中显示它们的详细信息的主要内容,如果未能解决你的问题,请参考以下文章

Firebase 实时数据库:如何迭代每个键值

如何限制用户在 Firebase 实时数据库中上传一定数量的数据

如何在 Firebase 实时数据库中搜索类似数组的数据?

如何从 Flutter 中的 Firebase 实时数据库中按 categoryId 获取产品?

使用flutter如何在同一个App中使用多个firebase实时数据库

遍历 Firebase 中一个孩子的所有键