Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get resource image by name into custom cursor adapter

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"

like image 801
Cuarcuiu Avatar asked Mar 04 '12 00:03

Cuarcuiu


1 Answers

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());
like image 165
MH. Avatar answered Oct 19 '22 17:10

MH.