如何通过OnclickListener传递Firestore文档的文档ID?

时间:2018-01-05 07:00:17

标签: android firebase android-recyclerview recycler-adapter google-cloud-firestore

我想将onClickListener添加到recyclerview中显示来自firestore的数据的项目。 OnClick应该通过intent传递相应的文档id。请求帮助

  • ProductFragment 显示数据

     public class ProductFragment extends Fragment {
    
        private static final String TAG = "ProductFragment";
        private FirebaseFirestore firestoreDB;
    private RecyclerView productRecyclerView;
    
    
    public ProductFragment() {
        // Required empty public constructor
    }
    
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
    
        View view =  inflater.inflate(R.layout.fragment_product, container, false);
        firestoreDB = FirebaseFirestore.getInstance();
        productRecyclerView = (RecyclerView) view.findViewById(R.id.Product_RecyclerView);
    
        LinearLayoutManager recyclerLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
        productRecyclerView.setLayoutManager(recyclerLayoutManager);
    
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(productRecyclerView.getContext(),
                                                                    recyclerLayoutManager.getOrientation());
        productRecyclerView.addItemDecoration(dividerItemDecoration);
    
        getDocumentsFromCollection();
    
    
        return view;
    
    }
    
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }
    
    
    public void getDocumentsFromCollection() {
        firestoreDB.collection("products").get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            //List<Event> eventList = new ArrayList<>();
                            List<DocumentSnapshot> documents = task.getResult().getDocuments();
    
    
                            ProductAdapter recyclerViewAdapter = new ProductAdapter(documents, getActivity(), firestoreDB);
    
    
    
                            recyclerViewAdapter.setOnItemClickListener(new ProductAdapter.ClickListener() {
                                @Override
                                public void onItemClick(int position, View v) {
                                    Log.d(TAG, "onItemClick position: " + position);
    
                                        // Go to the details page for the selected product
    
    
    
                                    }
    
                            });
    
                            productRecyclerView.setAdapter(recyclerViewAdapter);
    
    
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });
    
        firestoreDB.collection("products")
                .addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
    
    
                    }
                });
          }
    
    
     }
    
  • 适配器

    public class ProductAdapter  extends RecyclerView.Adapter<ProductAdapter.ViewHolder>{
    
    public static ClickListener clickListener;
    
    public List<DocumentSnapshot> documents;
    private Context context;
    private FirebaseFirestore firestoreDB;
    
    public ProductAdapter(List<DocumentSnapshot> list, Context ctx, FirebaseFirestore firestore) {
        documents = list;
        context = ctx;
        firestoreDB = firestore;
    }
    
    @Override
    public int getItemCount() {
        return documents.size();
    }
    
    @Override
    public ProductAdapter.ViewHolder
    onCreateViewHolder(ViewGroup parent, int viewType) {
    
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_layout, parent, false);
    
        ProductAdapter.ViewHolder viewHolder =
                new ProductAdapter.ViewHolder(view);
        return viewHolder;
    }
    
    @Override
    public void onBindViewHolder(ProductAdapter.ViewHolder holder, int position) {
        final int itemPos = position;
        final DocumentSnapshot snapshot = documents.get(position);
        holder.item_name.setText(snapshot.getString("Product"));
        holder.price.setText("Rs " + snapshot.getString("Cost") + "/" + snapshot.getString("Per"));
    
    
    }
    
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    
        public TextView item_name;
        public TextView price;
    
    
        public ViewHolder(View view) {
            super(view);
            itemView.setOnClickListener(this);
            item_name = view.findViewById(R.id.List_maintext);
            price = view.findViewById(R.id.List_subtext);
    
        }
    
        @Override
        public void onClick(View v) {
            clickListener.onItemClick(getAdapterPosition(), v);
    
        }
    }
    public void setOnItemClickListener(ClickListener clickListener) {
        ProductAdapter.clickListener = clickListener;
    
    
    }
    
    public interface ClickListener {
        void onItemClick(int position, View v);
    
    }
    
    }
    

我尝试了一些方法,但所有方法都崩溃了。 我需要显示点击项目的详细视图

1 个答案:

答案 0 :(得分:2)

你可以这样:创建POJO类并从这个类中获取数据。

<强> POJO.class

from PIL import ImageTk

你的片段,你的方法

public class Info {
String product;
String cost;
String per;
@Exclude
private String key;

public Info(){
}

public Info(String product, String cost, String per){
this.product = product;
this.cost = cost;
this.per = per;
}

public <T extends Info> T withId(@NonNull final String id) {
    this.key = id;
    return (T) this;
}

public String getProduct() {
    return product;
}

public void setProduct(String product) {
    this.product = product;
}

public String getCost() {
    return cost;
}
public void setCost(String cost) {
    this.cost = cost;
}

public String getPer() {
    return per;
}


public void setPer(String per) {
    this.per = per;
}
}

适配你的:

  List<Info> documents = new ArrayList<>(); //before onCreate method
  public void getDocumentsFromCollection() {
  firestoreDB.collection("products").get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
      for (DocumentSnapshot snap : task.getResult()){
                   Info model =snap.toObject(Info.class).withID(snap.getID());

   documents.add(model);


                    ProductAdapter recyclerViewAdapter = new     ProductAdapter(documents, getActivity(), firestoreDB);



                    recyclerViewAdapter.setOnItemClickListener(new ProductAdapter.ClickListener() {
                        @Override
                        public void onItemClick(int position, View v) {
                            Log.d(TAG, "onItemClick position: " + position);

                                // Go to the details page for the selected       product



                            }

                    });

                    productRecyclerView.setAdapter(recyclerViewAdapter);
                    productRecyclerView.notifyDataSetChanged();
       }

                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

firestoreDB.collection("products")
        .addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {


            }
        });
  }

您可以尝试这样的事情,我认为这可以帮助您解决问题。 附:对不起我的英语不好。