1

Similar question to Android: Set a random image using setImageResource, but I think I'm looking for a different answer.

As mentioned in the linked post, this:

int p = R.drawable.photo;
image.setImageResource(p);

displays photo1, but something like this:

String a = "R.drawable.";
String b = "photo";
String c = a+b;
int p = Integer.parseInt(c);
image.setImageResource(p);

will not. I have a lot of images, and an array contining all of the image names, so I want to fill an array something like:

int imageArray[] = new int[number_of_images];
for (int i = 0; i < numImages; i++)
imageArray[i] = ("R.drawable." + image_names[i]);

but I get a runtime error. Is there any way to make this loop work? Or better ways to cue up image ID's into an array?

Thanks!

3
  • Try printing p first. Is it the same as R.drawable.photo_id? Commented Jul 25, 2013 at 19:50
  • Is your issue similar to this: stackoverflow.com/questions/6945678/…? Commented Jul 25, 2013 at 19:52
  • Can you post the error? Commented Jul 25, 2013 at 19:55

1 Answer 1

1

You can use this method and it will retrun the source id based off a string. The second and third paramaters are optional but if you can put them in I would.

public int getIdentifier (String name, String defType, String defPackage) 

Example:

int p = getIdentifier("photo","drawable")

Or if you are getting ids all the time you could create a function like:

public int getDrawableId(Context context, String name){
    return context.getResources().getIdentifier(name,"drawable", context.getPackageName());
}

You just have to check to see if it returns 0 because that means it did not find it.

EDIT

For your example up there just impliment the function above and change it to this:

int imageArray[] = new int[number_of_images];
for (int i = 0; i < numImages; i++)
imageArray[i] = getDrawableId(getApplicationContext(),"R.drawable." + image_names[i]);
Sign up to request clarification or add additional context in comments.

Comments

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.