Load all images from assets folder dynamically

Kostas Drak picture Kostas Drak · Feb 2, 2015 · Viewed 11.3k times · Source

I am building an application that currently read images from the drawable folder. Since i cannot have subfolders in the drawable i have to create subfolders in the assets folder and load images from there. Is there any way that i can create a List or an ArrayList with all the images from the assets subfolder??

My code is this:

public class ImageAdapter extends BaseAdapter {

    private Context mContext;

    // Keep all Images in array
    public Integer[] mThumbIds = {
            R.drawable.pic_2,
            R.drawable.pic_3, R.drawable.pic_4,
            R.drawable.pic_5, R.drawable.pic_6,
            R.drawable.pic_7, R.drawable.pic_8,
            R.drawable.pic_9, R.drawable.pic_10,
            R.drawable.pic_11, R.drawable.pic_12,
            R.drawable.pic_13, R.drawable.pic_14,
            R.drawable.pic_15
    };

    // Constructor
    public ImageAdapter(Context c){
        mContext = c;
    }

    @Override
    public int getCount() {
        return mThumbIds.length;
    }

    @Override
    public Object getItem(int position) {
        return mThumbIds[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = new ImageView(mContext);
        imageView.setImageResource(mThumbIds[position]);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(250, 400));
        return imageView;
    }

}

Instead of having an Integer[] i want to have a List<String> or something like this from the assets subfolder

Any ideas???

Answer

ρяσѕρєя K picture ρяσѕρєя K · Feb 2, 2015

Is there any way that i can create a List or an ArrayList with all the images from the assets subfolder??

Yes, create sub-folder in assets directory. use getAssets().list(<folder_name>) for getting all file names from assets:

String[] images =getAssets().list("images");
ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));

Now to set image in imageview you first need to get bitmap using image name from assets :

InputStream inputstream=mContext.getAssets().open("images/"
                                      +listImages.get(position));
Drawable drawable = Drawable.createFromStream(inputstream, null);
imageView.setImageDrawable(drawable);