【问题标题】:Cards not updating after fetching data in Firestore在 Firestore 中获取数据后卡片未更新
【发布时间】:2020-08-07 10:20:49
【问题描述】:

我正在尝试为库存管理系统编写一个应用程序,我需要做的一件事是能够显示一个可以点击的类别列表,然后将您带到其中的产品列表类别。我正在使用带有 RecyclerView 的 CardView,它们都作用于片段(因为我正在使用导航抽屉)。如果传入预定义的 ArrayList,我能够成功显示卡片,但是当我现在从 Firestore 获取数据时,没有卡片希望出现,但我仍在使用相同的 ArrayList,但数据只是来自不同的来源。我仍然是 Android 的初学者,如果有人可以帮助我,我将不胜感激。这是我的 Fragment 类的代码。

package com.example.drawerplayground;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;


import java.util.ArrayList;
import java.util.HashMap;

public class InventoryFragment extends Fragment {

    private TextView tv;
    private HashMap<String, Object> categories;
    private ArrayList<String> cats;
    private FirebaseFirestore db;
    private InventoryAdapter adapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cats = new ArrayList<>();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View inventoryView = inflater.inflate(R.layout.fragment_inventory, container, false);
        RecyclerView recyclerView = (RecyclerView) inventoryView.findViewById(R.id.recycler_view);
        adapter = new InventoryAdapter(getContext(), cats);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(adapter);
        getCategories();
        return inventoryView;
    }

    public void getCategories()
    {
        cats = new ArrayList<>();
        db = FirebaseFirestore.getInstance();
        db.collection("categories")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if(task.isSuccessful())
                        {
                            for(QueryDocumentSnapshot document : task.getResult())
                            {
                                cats.add(document.get("categoryName").toString());
                                Log.d("fragment", document.get("categoryName").toString());
                            }
                        }
                    }
                });
        adapter.notifyDataSetChanged();
    }


}

我尝试使用适配器的notifyDataSetChanged() 方法,还尝试在单独的函数中执行数据获取,如上所示。

---编辑--- 下面你可以看到我对数据库结构的基本概念,我有一个类别的集合,每个文档都是一个不同的类别,每个文档将包含一个 id 和一个 categoryName 字段。目前它是一个非常基本且小型的结构,因为我的目标是在开始项目本身之前尝试使用潜在的功能。

【问题讨论】:

  • 请编辑您的问题并将您的数据库结构添加为屏幕截图。
  • Nikhil Sharma 能够很好地回答我的问题,但我仍然发布了数据库结构的屏幕截图以用于上下文。

标签: java android firebase android-recyclerview google-cloud-firestore


【解决方案1】:

我注意到您正在调用 adapter.notifyDataSetChanged(),但我无法找到您实际向适配器提供更新的猫列表的位置。

您应该调整您的适配器并进行以下更改-

添加setCatList()方法

public void setCatList(List<String> catList) {
    this.catList= catList;
    notifyDataSetChanged();
}

修改你的getItemCount() 方法

@Override
public int getItemCount() {
    if (catList!= null)
        return catList.size();
    else
        return 0;
}

因此,您的 InventoryAdapter 的结构如下-

public class InventoryAdapter extends RecyclerView.Adapter<InventoryAdapter.CustomViewHolder> {

    private Context context;
    private List<String> catList;

    public InventoryAdapter(Context context) {
        this.context = context;
    }
    
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.cat_item_layout, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
    // setup binding of views
    }

    public void setCatList(List<String> catList) {
        this.catList= catList;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        if (catList!= null)
            return catList.size();
        else
            return 0;
    }

    //inner class of CustomViewHolder
}

那么你在onCreate()onCreateView()不需要创建new ArrayList&lt;&gt;()。这就是您创建适配器的方式 -

adapter = new InventoryAdapter(getContext());

getCategories()将如下-

public void getCategories()
{
    db = FirebaseFirestore.getInstance();
    db.collection("categories")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if(task.isSuccessful())
                    {
                        List<String> cats = new ArrayList();
                        for(QueryDocumentSnapshot document : task.getResult()){
                            cats.add(document.get("categoryName").toString());
                            Log.d("fragment", document.get("categoryName").toString());
                        }
                        adapter.setCatList(cats ); //simply give updated cats list to recycle adapter
                    }
                }
            });
}

无需调用adapter.notifyDataSetChanged(),因为这将在适配器的setCatList() 方法下处理。

如果您想保留 catList,那么您可以相应地修改setCatList(),如进行 if 检查,是否已经存在某些数据,如下所示 -

public void setCatList(List<String> catList) {
    if(this.catList!=null){
        if(this.catList.size()!=0){
            //there is some cat item inside already, take action accordingly 
        }
        else
            this.catList= catList;
    }
    else{
        this.catList= catList;
    }
   
    notifyDataSetChanged();
}

编码愉快!

【讨论】:

  • 感谢您提供的惊人帮助,您所做的事情更有意义。
  • 我相信编程只是另一种有意义的方式:),很高兴你发现它有帮助......干杯队友!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2020-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多