I have a custom cursor adapter and I'd like to put an image into a ImageView in a ListView.
My code is:
public class CustomImageListAdapter extends CursorAdapter {
private LayoutInflater inflater;
public CustomImageListAdapter(Context context, Cursor cursor) {
super(context, cursor);
inflater = LayoutInflater.from(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// get the ImageView Resource
ImageView fieldImage = (ImageView) view.findViewById(R.id.fieldImage);
// set the image for the ImageView
flagImage.setImageResource(R.drawable.imageName);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.row_images, parent, false);
}
}
This is all OK but I would like to get the name of image from database (cursor). I tried with
String mDrawableName = "myImageName";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
But return error: "The method getResources() is undefined for the type CustomImageListAdapter"
You can only do a getResources()
call on a Context object. Since the CursorAdapter
's constructor takes such a reference, simply create a class member that keeps track of it so that you can use it in (presumably) bindView(...)
. You'll probably need it for getPackageName()
too.
private Context mContext;
public CustomImageListAdapter(Context context, Cursor cursor) {
super(context, cursor);
inflater = LayoutInflater.from(context);
mContext = context;
}
// Other code ...
// Now call getResources() on the Context reference (and getPackageName())
String mDrawableName = "myImageName";
int resID = mContext.getResources().getIdentifier(mDrawableName , "drawable", mContext.getPackageName());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With