I have a list of data from my API call into my RecyclerView
. I have an itemClickListener
interface that opens a new fragment with item image and details.
When I click on the item, I need to pass data to the 2nd fragment and it's adapter. How will it work?
Do I need to send this data with a bundle and then make another API call inside my 2nd fragment? Or just the bundle with data which I can use without an additional API call?
This is my model:
public class Products {
private String productId;
private String productName;
private String shortDescription;
private String longDescription;
private String price;
@SerializedName("productImage")
private String image;
@SerializedName("reviewRating")
private double rating;
private int reviewCount;
private boolean inStock;
public String getProductId() {
return productId;
}
public String getProductName() {
return productName;
}
public String getShortDescription() {
return shortDescription;
}
public String getLongDescription() {
return longDescription;
}
public String getPrice() {
return price;
}
public String getImage() {
return image;
}
public double getRating() {
return rating;
}
public int getReviewCount() {
return reviewCount;
}
public boolean isInStock() {
return inStock;
}
}
this is my MainFragment:
private void setBundle(int position) {
args = new Bundle();
String[] clickedItem = {apiProducts.get(position).getImage(),
apiProducts.get(position).getLongDescription(),
String.valueOf(apiProducts.get(position).isInStock())};
args.putStringArray("Item", clickedItem);
}
private void productsClickListener() {
if (apiObjectAdapter != null) {
apiObjectAdapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(View itemView, int position) {
setBundle(position);
setDetailsFragment(args);
}
});
}
}
My adapter:
public class ApiObjectAdapter extends RecyclerView.Adapter<ApiObjectAdapter.MyViewHolder> {
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.product_name)
public TextView name;
@BindView(R.id.product_rating)
public TextView rating;
@BindView(R.id.product_price)
public TextView price;
public MyViewHolder(final View view) {
super(view);
this.parentView = view;
try {
ButterKnife.bind(this, view);
} catch (Exception e) {
e.printStackTrace();
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null)
listener.onItemClick(view, getLayoutPosition());
}
});
}
}