0

I'm using OpenGL ES to make a game in Android. I got some code from a tutorial and I'm trying to change it to suit my app but I'm having a problem. I want to dynamically get an image resource using a string passed into a function as the resource name. I know usually you use getIdentifier() in this case, but that returns an int and I need an input stream. Is there any way of getting an input stream from a resource dynamically?

Alternatively, is there a better way of doing this?

Code below:

InputStream is = mContext.getResources().openRawResource(R.drawable.<imagename>);

Bitmap bitmap;
try {
      bitmap = BitmapFactory.decodeStream(is);
}
finally {
      try {
            is.close();
      } 
      catch (IOException e) {
            e.printStackTrace();
      }
}
Jean Finley
  • 507
  • 3
  • 9
  • 21

1 Answers1

1

yes u can Suppose u have images stored in drawable with naming img1,img2,img3,img4,img5,img6,img7 than first make an array like

String[] imgarray={"img1","img2","img3","img4","img5","img6","img7"};
public static String PACKAGE_NAME ;
PACKAGE_NAME=getApplicationContext().getPackageName();
Random r = new Random();
int n=r.nextInt(imgarray.length());
int resID = getResources().getIdentifier( PACKAGE_NAME+":drawable/" +imgarray[n] , null, null);  
imageview.setImageResource(resID);

if want bitmap image than just add below line

Bitmap  bm = BitmapFactory.decodeResource(getResources(),resID);

if u want other way with less coding than see accepted answer at Other Example

Community
  • 1
  • 1
Khan
  • 7,585
  • 3
  • 27
  • 44