Search code examples
androidandroid-imageuniversal-image-loader

Android - Using Universal Image Loader in static class


Can I use Universal Image Loader lib in a static class? Meaning creating one instance of image loader and modifying it to static.

What is the best method to use this lib in different multiple fragments and classes? How can I improve caching feature?


Solution

  • The best way to use Universal Image Loader is to create a single instance when your App starts up and then get that instance throughout the app

    Here is the App class

     public class App extends Application {
    
        public ImageLoader imageLoader;
    
        public ImageLoader getImageLoader() {
            return imageLoader;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            // UNIVERSAL IMAGE LOADER SETUP
            DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                    .resetViewBeforeLoading(true)
                    .cacheOnDisk(true)
                    .cacheInMemory(true)
                    .displayer(new FadeInBitmapDisplayer(300))
                    .build();
    
            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                    .defaultDisplayImageOptions(defaultOptions)
                    .memoryCache(new WeakMemoryCache())
                    .diskCacheSize(100 * 1024 * 1024)
                    .build();
    
            this.imageLoader = ImageLoader.getInstance();
            imageLoader.init(config);
    
            // END - UNIVERSAL IMAGE LOADER SETUP
        }
    }
    

    Make sure the application tag in AndroidManifest.xml has android:name=”.App” attribute

    To get the instance, in an Activity

    ImageLoader imageLoader = ((App)getApplicationContext()).getImageLoader();
    

    outside Activity

    ImageLoader imageLoader = ((App)context.getApplicationContext()).getImageLoader();
    

    You can refer this blog.