0

I have this code where I want to set an image from a string:

String imagename = "mypicture";
ImageView lblPic = new ImageView(this);
int resID = getResources().getIdentifier(imagename, "drawable", getPackageName());
lblPic.setImageResource(resID);

This is my xml file.

<ImageView  android:layout_width="wrap_content"
 android:layout_height="wrap_content" 
 android:id="@+id/image1" android:src="@drawable/no_image" /> 

Where could there be a problem? I think I've setup xml file wrong...? I've tried many codes but every time Java code doesn't change the picture, it stays as it was in xml file.

1 Answer 1

1

Correct :

  <ImageView  
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" 
          android:id="@+id/image1" 
          android:src="@drawable/no_image" />

Place this line in onCreate Method of your Activity :

ImageView lblPic = (ImageView) findViewById(R.id.image1);
int resID = getResources().getIdentifier(imagename, "drawable", getPackageName());
lblPic.setImageResource(resID);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. And i found out that i have to use filename without extension :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.