【问题标题】:Notify changes of Firestore data in RecyclerView通知 RecyclerView 中 Firestore 数据的变化
【发布时间】:2020-03-23 00:04:28
【问题描述】:

在我的应用程序中有一个片段,其中包含一个可扩展的 RecyclerView 从 firebase firestore 获取数据,其中的每个项目都有一个按钮,当单击该按钮时,会更改 Firestore 中以某种方式影响项目的某些数据。 现在的问题是:当运行应用程序并单击按钮时,数据不会改变,直到我刷新片段..

片段.java:

View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
final String UserId = currentUser.getUid();

final RecyclerView recyclerView = root.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

db.collectionGroup("Id").whereEqualTo("id", UserId).get()
  .addOnCompleteListener(new OnCompleteListener < QuerySnapshot > () {
    @Override
    public void onComplete(@NonNull Task < QuerySnapshot > task) {
        final List < Company > Parent = new ArrayList < > ();

        for (QueryDocumentSnapshot document: task.getResult()) {
            final List < String > grades = (List < String > ) document.get("tagsG");

            CollectionReference collectionReference =
                document.getReference().getParent();
            final List < Product > Child = new ArrayList < > ();
            for (int i = 0; i < grades.size(); i++) {
                final String gg = grades.get(i);
                collectionReference.document(UserId).collection(gg).whereEqualTo("approvedStd",0).get()
                    .addOnCompleteListener(new OnCompleteListener < QuerySnapshot > () {
                        @Override
                        public void onComplete(@NonNull Task < QuerySnapshot > task) {
                            for (QueryDocumentSnapshot document: task.getResult()) {
                                String name = document.getString("std_name");
                                String sub = document.getString("std_subject");
                                String region = document.getString("std_region");
                                Child.add(new Product(name, sub, region, gg));
                            }
                        }
                    });
            }
            Parent.add(new Company("new", Child));
            productAdapter = new ProductAdapter(Parent);
            recyclerView.setAdapter(productAdapter);
        }
    }
});
return root;

ViewHolder.java

public class ProductViewHolder extends ChildViewHolder {
    private FirebaseFirestore db = FirebaseFirestore.getInstance();
    private FirebaseAuth mAuth = FirebaseAuth.getInstance();
    private FirebaseUser currentUser = mAuth.getCurrentUser();
    private String UserId = currentUser.getUid();
    private TextView name;
    private TextView sTextView;
    private TextView region;
    private Button addButton;
    private String phoneOfstd;
    private String grade;
    private ProductAdapter productAdapter;

    public ProductViewHolder(View itemView) {
        super(itemView);
        name = itemView.findViewById(R.id.name);
        sTextView = itemView.findViewById(R.id.sub);
        region = itemView.findViewById(R.id.region);
    }

    public void bind(Product product) {
        name.setText(product.name);
        sTextView.setText(product.sub);
        region.setText(product.region);
        grade = product.grade;

        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                CollectionReference questionsRef = db.collection("Teachers checked").document("courses").collection("Id");
                DocumentReference docRef = questionsRef.document(UserId).collection(grade).document(phoneOfstd);
                docRef.update("approvedStd", 1);
                productAdapter.notifyDataSetChanged();
            }
        });
    }

}

ProductAdapter.java

public class ProductAdapter extends
 ExpandableRecyclerViewAdapter < CompanyViewHolder, ProductViewHolder > {
    public ProductAdapter(List < ? extends ExpandableGroup > groups) {
        super(groups);
    }

    @Override
    public CompanyViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.expandable_recyclerview_company, parent, false);
        return new CompanyViewHolder(v);
    }

    @Override
    public ProductViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.expandable_recyclerview_product, parent, false);
        return new ProductViewHolder(v);
    }

    @Override
    public void onBindChildViewHolder(ProductViewHolder holder, int flatPosition, ExpandableGroup group, int childIndex) {
        final Product product = (Product) group.getItems().get(childIndex);
        holder.bind(product);
    }

    @Override
    public void onBindGroupViewHolder(CompanyViewHolder holder, int flatPosition, ExpandableGroup group) {
        final Company company = (Company) group;
        holder.bind(company);
    }
}

编辑:

我尝试在 recyclerView.setAdapter(productAdapter); 之后的片段中写入 productAdapter.notifyDataSetChanged(); 但应用程序崩溃并且 logcat 显示此错误:

致命异常:主要 java.lang.NullPointerException:尝试 调用虚方法'void com.example.exercise.ExpandableRecyclerView.ProductAdapter。 空对象引用上的 notifyDataSetChanged()'

【问题讨论】:

  • 尝试在片段productAdapter.notifyDataSetChanged()中添加这一行;
  • @MarsadMaqsood 你能告诉我具体写在哪里吗?因为我试过了,但是应用崩溃了
  • 在片段下面的``` Parent.add(new Company("new", Child));产品适配器 = 新产品适配器(父); recyclerView.setAdapter(productAdapter); ``` ``` productAdapter.notifyDataSetChanged(); ```希望这行得通
  • 我建议你使用这个库实现 'com.firebaseui:firebase-ui-firestore:6.2.0'

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


【解决方案1】:

这里可能是你的错误docRef.update("approvedStd", 1); productAdapter.notifyDataSetChanged();

您更新了 firestore 中的对象,但您没有实现 EventListener 以在发生任何更改后检索数据,因此您有两个选项来更新 arrayList 中的此对象并调用 notifydatasetChanged 或添加 Snapshotlistener 以在执行任何更改后检索数据

【讨论】:

    【解决方案2】:

    首先,您的productAdapter 等于null,因为您没有为它分配任何值,您应该将您的适配器的引用传递给视图持有者。

    其次,主要的问题是当你点击item中的一个view时需要更新view。

    1-在bind方法中绑定视图时处理变化。

    2- 当您单击 btn 或视图时,您应该通过需要显示的更改来更新对象。

    3- 如果更改影响当前项目,则仅使用

    notifyItemChanged(position, object)
    

    如果它影响到你应该使用的许多项目

    notifyDataSetChanged()
    

    例如: 如果你有复选框并且你需要让它在你的回收站中工作。

    1-在bind方法中绑定复选框

    checkbox.setChecked(product.isSelected());
    

    2- 在检查更改事件中,我们将更新产品对象

    product.setSelected(isChecked);
    

    3- 在检查更改事件结束时

    notifyItemChanged(getAdapterPosition(), product);
    

    【讨论】:

      【解决方案3】:

      您可以在适配器中放置一个读取数据的函数,以确保您的数据得到更新。我在这里看不到你的适配器的代码,但试试这个,让我知道它是否解决了。

      【讨论】:

      • 你能解释更多吗?我编辑了Q并添加了Adapter的代码..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 2021-12-27
      相关资源
      最近更新 更多