Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load all images from assets folder dynamically

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???

like image 893
Kostas Drak Avatar asked Feb 02 '15 11:02

Kostas Drak


2 Answers

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);
like image 146
ρяσѕρєя K Avatar answered Oct 27 '22 16:10

ρяσѕρєя K


String[] images =getAssets().list("images"); returns the content of folder "images" in assetes.

If your assets folder directly contains images them u should use

String[] images =getAssets().list("");
like image 3
Sonia John Kavery Avatar answered Oct 27 '22 16:10

Sonia John Kavery