Search code examples
androidimage-loading

Initialization of ImageLoaders on App Launch


How can i initialize image loader on app launch so i can use it everywhere in my application.I am trying to use volley library.

 if (mImageLoader == null) {
        mImageLoader = new ImageLoader(this.mRequestQueue,
                new LruBitmapCache());
    }

Solution

  • I would create a singleton. Here's an example from a project I posted:

    public class VolleySingleton {
    
        private static Context mContext;
        private RequestQueue mRequestQueue;
        private ImageLoader mImageLoader;
    
        private static VolleySingleton ourInstance;
        public static VolleySingleton getInstance(Context context) {
            if (ourInstance == null) {
                ourInstance = new VolleySingleton(context);
            }
            return ourInstance;
        }
    
        private VolleySingleton(Context context) {
            mContext=context;
            mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());
            mImageLoader = new ImageLoader(mRequestQueue,
                    new ImageLoader.ImageCache() {
                        private final LruCache<String, Bitmap>
                                cache = new LruCache<String, Bitmap>(20);
                        @Override
                        public Bitmap getBitmap(String url) {
                            return cache.get(url);
                        }
                        @Override
                        public void putBitmap(String url, Bitmap bitmap) {
                            cache.put(url, bitmap);
                        }
                    });
        }
    
        public <T> void addToRequestQueue(Request<T> req) {
            mRequestQueue.add(req);
        }    
    
        public ImageLoader getImageLoader() {
            return mImageLoader;
        }
    }
    

    Then you can get the image loader with this statement:

    VolleySingleton.getInstance(this).getImageLoader();