Issue
What I'm trying to do is to load some images from drawable. In fact, I want to load the images like R.drawable."string"
but unfortunately can't find a way to fit the string into it. Also, the string is loaded from a MySQL DB.
Here you can see the code.
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private Context mContext;
private ArrayList<Product> mProducts;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public ProductAdapter(Context context, ArrayList<Product> products) {
mContext = context;
mProducts = products;
}
@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.product, parent, false);
return new ProductViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull ProductViewHolder holder, int position) {
Product currentProduct = mProducts.get(position);
String name = currentProduct.getName();
String photo = currentProduct.getPhoto();
double price = currentProduct.getPrice();
holder.textViewName.setText(name);
holder.textViewPrice.setText(price + "€");
int id = mContext.getResources().getIdentifier(photo, "drawable", mContext.getPackageName());
Picasso.get().load(id).into(holder.imageView);
}
@Override
public int getItemCount() {
return mProducts.size();
}
public class ProductViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public TextView textViewName;
public TextView textViewPrice;
public ProductViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_view);
textViewName = itemView.findViewById(R.id.textViewName);
textViewPrice = itemView.findViewById(R.id.textViewPrice);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
As you can see I tried the int id = mContext.getResources().getIdentifier(photo, "drawable", mContext.getPackageName());
that I found googling around, but doesn't seem to work...
I really appreciate any help you can provide.
Solution
I would suggest another approach instead of the one you need to use: you can have a conditional on what is returned from MySQL database, and return id (R.drawable.xx) accordingly like below:
int id;
if(photo.equals("foo")) {
id = R.drawable.foo;
} else if(photo.equals("bla")) {
id = R.drawable.bla;
} else {
id = // default id
}
Picasso.get().load(id).into(holder.imageView);
So, this way each drawable has one particular mapping in database.
Answered By - Zain
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.