zaheer
zaheer

Reputation: 143

Android loading images from drawable using java code

i Have more than 1000 images in my drawable folder, and i need to load all these images in an array-list in order to search later when the program running. Is there any possible way in android that i can load all the images in an ArrayList dynamically?

thanks

Upvotes: 0

Views: 527

Answers (3)

zaheer
zaheer

Reputation: 143

This is the final working code:

 ImageView imageView = findViewById(R.id.testImage);
    //load all the icon names from drawable
    ArrayList<String> arrayOfIcons = new ArrayList<>();

    //load the array containing specific characters
    containingArray = new ArrayList<>();

    Field[] drawables = R.drawable.class.getFields();
    for (Field f : drawables) {
        try {
            int resID = getResources().getIdentifier(f.getName() , "drawable", getPackageName());
            arrayOfIcons.add(f.getName());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //search for all similar keywords
    for(int i =0; i < arrayOfIcons.size();i++){
        if(arrayOfIcons.get(i).contains(title_string) && arrayOfIcons.get(i).contains("_")){
            containingArray.add(arrayOfIcons.get(i));
        }
    }
    //split array
    for(int i = 0; i < containingArray.size();i++){

        //finding the index that contains the keyword 
        if(containingArray.get(i).substring(0,containingArray.get(i).lastIndexOf("_")).equalsIgnoreCase(title_string)){
            Context context = imageView.getContext();
            int id = context.getResources().getIdentifier(containingArray.get(i), "drawable", context.getPackageName());
            imageView.setImageResource(id);
        }
        System.out.println("ContainingArray: "+containingArray.get(i));
    }

Upvotes: 0

aNiKeT
aNiKeT

Reputation: 96

import java.lang.reflect.Field;

Field[] ID_Fields = R.drawable.class.getFields();
int[] resArray = new int[ID_Fields.length];
for(int i = 0; i < ID_Fields.length; i++) {
    try {
        resArray[i] = ID_Fields[i].getInt(null);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Upvotes: 0

Juanjo Berenguer
Juanjo Berenguer

Reputation: 789

This code is working and tested by me, you can get all images from drawable and save it in an ArrayList.

But in my opinion that is a very very bad idea

Code:

 ArrayList<Integer> arrayOfIcons = new ArrayList<>();

Field[] drawables = R.drawable.class.getFields();
for (Field f : drawables) {
    try {
        int resID = getResources().getIdentifier(f.getName() , "drawable", getPackageName());
        arrayOfIcons.add(resID);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

ImageView imageView = findViewById(R.id.imageView);
imageView.setImageResource(arrayOfIcons.get(0));

I hope it helps you.

Upvotes: 3

Related Questions