Get resource image by name in custom cursor adapter

I have a custom cursor adapter, and I would like to put an image in an 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 fine, but I would like to get the image name from the database (cursor). I tried using

 String mDrawableName = "myImageName"; int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName()); 

But the error returned is: "The getResources () method is undefined for the type CustomImageListAdapter"

+6
source share
1 answer

You can only call getResources() on a Context object. Since the CursorAdapter constructor accepts such a link, simply create a member of the class that tracks it so you can use its (presumably) bindView(...) . You might need this for getPackageName() .

 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()); 
+13
source

Source: https://habr.com/ru/post/909909/


All Articles