How to display data from Firestore in a RecyclerView with Android?

前端 未结 1 1644
不思量自难忘°
不思量自难忘° 2020-11-22 08:01

What is the best way to display data from an existing Firestore database in a RecyclerView using Android?

This isn\'t covered as a full explanation in a

相关标签:
1条回答
  • 2020-11-22 09:00

    Assuming you have a Firestore database structure that looks like this:

    Firestore-root
        |
        --- products (collection)
               |
               --- documentIdOne (document)
               |        |
               |        --- productName: "Milk"
               |
               --- documentIdTwo (document)
               |        |
               |        --- productName: "Soy Milk"
               |
               --- documentIdThree (document)
                        |
                        --- productName: "Bacon"
    

    A model class that looks also like this:

    public class ProductModel {
        private String productName;
    
        public ProductModel() {}
    
        public ProductModel(String productName) {this.productName = productName;}
    
        public String getProductName() {return productName;}
    }
    

    And a .XML file that contains a RecyclerView which also looks like this:

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recycler_view"/>
    

    To display all the product names, please follow the next steps.

    First, you need to find the RecyclerView in your activity and set the LinearLayoutManager like this:

    RecyclerView recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    

    Then you need to create the root reference of your Firestore database and a Query object like this:

    FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    Query query = rootRef.collection("products")
            .orderBy("productName", Query.Direction.ASCENDING);
    

    Then you'll have to create a FirestoreRecyclerOptions object like this:

    FirestoreRecyclerOptions<ProductModel> options = new FirestoreRecyclerOptions.Builder<ProductModel>()
            .setQuery(query, ProductModel.class)
            .build();
    

    In your activity class, create a holder class that looks like this:

    private class ProductViewHolder extends RecyclerView.ViewHolder {
        private View view;
    
        ProductViewHolder(View itemView) {
            super(itemView);
            view = itemView;
        }
    
        void setProductName(String productName) {
            TextView textView = view.findViewById(R.id.text_view);
            textView.setText(productName);
        }
    }
    

    Then create an adapter which is declared as global:

    private FirestoreRecyclerAdapter<ProductModel, ProductViewHolder> adapter;
    

    And instantiate it in your activity like this:

    adapter = new FirestoreRecyclerAdapter<ProductModel, ProductViewHolder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull holder productViewHolder, int position, @NonNull ProductModel productModel) {
            holder.setProductName(productModel.getProductName());
        }
    
        @NonNull
        @Override
        public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_product, parent, false);
            return new ProductViewHolder(view);
        }
    };
    recyclerView.setAdapter(adapter);
    

    In the end, don't forget to override the following two methods and start listening for changes:

    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }
    
    @Override
    protected void onStop() {
        super.onStop();
    
        if (adapter != null) {
            adapter.stopListening();
        }
    }
    

    The result is this:

    Edit:

    If you want to display a toast message when the user clicks on an item, please add the following lines of code inside the setProductName() method from the ProductViewHolder class:

    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(), productName, Toast.LENGTH_SHORT).show();
        }
    });
    
    0 讨论(0)
提交回复
热议问题