0

Here is my code, I have 100 images and i want to create it dynamic using loop but it's not working.

   int[] imgIds = {R.drawable.img1, R.drawable.img2, R.drawable.img3};
3
  • What is the problem that you are facing? What is not working? Your question states a loop but there is no loop in the code snippet that you posted Commented Apr 7, 2014 at 9:36
  • What problem you are facing ? also share code which you have tried Commented Apr 7, 2014 at 9:37
  • I am just asking how to create it dynamically.this is just simple and i don't want to write 100 images name in array. Commented Apr 7, 2014 at 9:39

2 Answers 2

1

Try using getResources().getIdentifier to create array of drawable id's if drawables name is as img1,img2,img3,..

int[] imgIds = new int [100];
int imagecount=1;
for(int i=0;i<100;i++){
imgIds[i]=getResources().getIdentifier("img"+imagecount,
                                           "drawable", getPackageName());
imagecount++;
}
Sign up to request clarification or add additional context in comments.

Comments

1

if your images are all called with the same prefix and the only thing it does change is the number you can do the following thing:

Suppose you numbered from 0 to size -1

ArrayList<Integer> imgIds = new ArrayList<Integer>();
for (int i = 0; i < size; i++) {
  imgIds.add(getResources().getIdentifier("img"+i, "drawable", getPackageName());
}

check for typo. Edit. With array:

int[] imgIds = new int[size];
for (int i = 0; i < size; i++) {
  imgIds[i] = getResources().getIdentifier("img"+i, "drawable", getPackageName();
}

3 Comments

I want to implement it using array not array list.
When I am trying to put your code but it gives error "null pointer" public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext; ArrayList<Integer> mImageIds = new ArrayList<Integer>(); for (int i = 0; i < size; i++) {mImageIds.add(getResources().getIdentifier("img"+i, "drawable", getPackageName()); } }
where do you get the NPE? post the stacktrace

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.