1

I am wondering how i can set a Bitmap drawable resource from a dynamic variable that is the image name/ type string:

public CustomIcon getView(int position, View convertView, ViewGroup parent) {
        String label;
        String image;
        DataBaseManager db = new DataBaseManager(context);
        label = db.getIconLabel(mIcons.get(position));
        image = db.getIconImage(mIcons.get(position));
        Bitmap bitmap = BitmapFactory.decodeResource(parent.getResources(),
                parent.getResources().getIdentifier(image, "drawable", getApplicationContext().getPackageName()));
        Log.v(TAG, "current pos:"+ position);
        CustomIcon icon = new CustomIcon(context, bitmap,label);

        return icon;
    }

the part in question is

Bitmap bitmap = BitmapFactory.decodeResource(parent.getResources(),
                         R.drawable.[image]);

CODE CHANGED ABOVE -

ƒernando Valle
  • 3,634
  • 6
  • 36
  • 58
erik
  • 4,946
  • 13
  • 70
  • 120

1 Answers1

1

The way to deal with this is to get the resource ID first and then use the BitmapFactory method:

String imgName = "myicon";
int resID = parent.getResources().getIdentifier(imgName, "drawable", "my.app.package.name");
Bitmap bitmap = BitmapFactory.decodeResource(parent.getResources(), resID);
Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • ah thanks i was just coming back to close this thread,.. i ended up doing it a little different than you suggested and am updating the code above.. is there a an advantage to doing it your way or mine? see above edit - – erik Mar 08 '12 at 17:25