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());
Share:
10,137
Cuarcuiu
Author by

Cuarcuiu

Php Senior Developer

Updated on June 22, 2022

Comments

  • Cuarcuiu
    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
    Cuarcuiu about 12 years
    Thank to "MH." for the solution. (also to "MisterSquonk")
  • Ricardo
    Ricardo over 9 years
    Why can you use getResources() without appending the context inside an Activity? Thanks.
  • MH.
    MH. over 9 years
    @Ricardo: Because Activity (indirectly) extends from Context. However, there is nothing preventing you from writing this.getResources(), which is exactly the same thing, but explicitly includes the object it is called on (where this is a reference to the instance of the Activity, and thus Context).
  • Ricardo
    Ricardo over 9 years
    Thanks @MH, I didn't know that.