【问题标题】:How to pass document id of Firestore document through OnclickListener?如何通过 OnclickListener 传递 Firestore 文档的文档 ID?
【发布时间】:2018-06-14 23:26:33
【问题描述】:

我想将 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);
    
    }
    
    }
    

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

【问题讨论】:

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


【解决方案1】:

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

POJO.class

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) {


            }
        });
  }

适应你的:

public class ProductAdapter  extends  RecyclerView.Adapter<ProductAdapter.ViewHolder>{

public static ClickListener clickListener;

public List<Info> documents;
private Activity context;
private FirebaseFirestore firestoreDB;

public ProductAdapter(List<Info> list, Activitx 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 Info model = documents.get(position);
 holder.item_name.setText(model.getProduct());
  holder.price.setText("Rs " + model.getCost() + "/" +  model.getPer());

  holder.itemView.setOnClicListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent openNewActivity = new Intent(context, YourNewActivity.class);
              openNewActivity.putExtra("id", model.getId());
              openNewActivity.putExtra("product", model.getProduct());
              context.startActivity(openNewActivity);
            }
        }); 


 }

 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);

}

}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2018-10-07
    • 2018-08-27
    • 2020-05-12
    • 2022-01-05
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多