Get resource image by name into custom cursor adapter
10,137
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());
Comments
-
Cuarcuiu almost 2 years
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"
-
Cuarcuiu about 12 yearsThank to "MH." for the solution. (also to "MisterSquonk")
-
Ricardo over 9 yearsWhy can you use getResources() without appending the context inside an Activity? Thanks.
-
MH. over 9 years@Ricardo: Because
Activity
(indirectly) extends fromContext
. However, there is nothing preventing you from writingthis.getResources()
, which is exactly the same thing, but explicitly includes the object it is called on (wherethis
is a reference to the instance of theActivity
, and thusContext
). -
Ricardo over 9 yearsThanks @MH, I didn't know that.