Search code examples
androidarraylistbitmapuniversal-image-loader

android - loading Bitmaps into array with UniversalImageLoader


I'm trying to fill arraylist with Bitmaps and here is my code:

ImageLoader imageLoader = ImageLoader.getInstance();
    ArrayList<Bitmap> imgArray = new ArrayList<>();
    for (int num=0;num<4;num++) {
        imgArray.add(num,imageLoader.loadImageSync("http://example.com/sample.jpg"));
    }

But I'm getting a NullPointerException, though loadImageSync(uri) should've returned Bitmap as stated in the Documentation on GitHub. How to fix the problem?


Solution

  • Configuration:

    File cacheDir = StorageUtils.getOwnCacheDirectory(
                    getApplicationContext(),
                    "/sdcard/Android/data/random_folder_name_for_cache");
    
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .cacheInMemory(true).cacheOnDisc(true).build();
    
            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                    getApplicationContext()).defaultDisplayImageOptions(options)
                    .discCache(new FileCountLimitedDiscCache(cacheDir, 100))
                    .build();
    
            ImageLoader.getInstance().init(config);
    
    
    final ArrayList<Bitmap> imgArray = new ArrayList<>(); // this should be a public array outside of the method scope. a member of the activity
    for (int num=0;num<4;num++) {
        ImageLoader imageLoader = ImageLoader.getInstance(); 
        int final constNum = num;
        imageLoader.loadImage("http://example.com/sample.jpg", new SimpleImageLoadingListener() 
        {
            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) 
            {
               imgArray.add(constNum, loadedImage);
            }
        });        
    }