Shaken Bissenkulov
Shaken Bissenkulov

Reputation: 31

How to get the name of the image which is allocated in drawable folder?

In my Android application, in SQLite db, I have a picture attribute of type String.

The following code works and allows me to retrieve image from drawable folder and display it in the ImageView.

protected ImageView pictureView;
...
pictureView = (ImageView) findViewById(R.id.pictureView);
pictureView.setImageDrawable(getResources().getDrawable(R.drawable.howard));
// howard.png is my image

The problem is that I can't get the images of my objects dynamically because my code for generating string that represents the name of the image in drawable doesn't seem to work.

I tried to do it these ways but it doesn't work.

1st way:

Resources res = getResources();
String picture = cursor.getString(cursor.getColumnIndex("picture"));
int id = getResources().getIdentifier("samples.companydirectory.drawable/" + picture, null, null);
Drawable drawable = res.getDrawable(id);
pictureView.setImageDrawable(drawable);

2nd way:

pictureView = (ImageView) findViewById(R.id.pictureView);
String picture = cursor.getString(cursor.getColumnIndex("picture"));
int id = getResources().getIdentifier("samples.companydirectory.drawable/" + picture, null, null);
pictureView.setImageResource(id);

XML code:

<ImageView
            android:id="@+id/pictureView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

What am I doing wrong?

Upvotes: 0

Views: 1006

Answers (1)

Igor Ronner
Igor Ronner

Reputation: 1584

I have a class like so many things

public static int getResourceId(Context context, String name)
   {
       int resourceId = context.getResources().getIdentifier(name, "drawable", context.getPackageName());       
       return resourceId;
   }

In your case is well

pictureView = (ImageView) findViewById(R.id.pictureView);
String picture = cursor.getString(cursor.getColumnIndex("picture"));
int id = getResources().getIdentifier(picture, "drawable", context.getPackageName());
pictureView.setImageResource(id);

Upvotes: 1

Related Questions