Sohail Zahid February 2016

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());
    }

Answers


NightSkyDev February 2016

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();


Igor Monochkov February 2016

Try this:

public class Application extends android.app.Application {

    @Override
    public void onCreate() {
        super.onCreate();

        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .defaultDisplayImageOptions(defaultOptions)
                .build();
        ImageLoader.getInstance().init(config);
    }
}

Post Status

Asked in February 2016
Viewed 2,569 times
Voted 8
Answered 2 times

Search




Leave an answer