Skip to content Skip to sidebar Skip to footer

Instantiating Core Volley Objects

What I'm a bit unsure about with Volley is the RequestQueue, ImageLoader objects and ImageLoader.ImageCache implementations.. In the examples I have come across they are instantia

Solution 1:

My experience with Volley is that I would initiate a RequestQueue inside of the Application class passing it a global context to the application. I can't see the downside to doing this just make a static reference to the RequestQueue as such:

publicclassMyApplicationextendsApplication
{
    privatestatic RequestQueue mRequestQueue;

    @OverridepublicvoidonCreate() {
        super.onCreate();
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    // Getter for RequestQueue or just make it public
}

In the documentation as you can for the Application class it quotes:

Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created. Implementations should be as quick as possible (for example using lazy initialization of state) since the time spent in this function directly impacts the performance of starting the first activity, service, or receiver in a process. If you override this method, be sure to call super.onCreate().

So it is safe to assume our RequestQueue will be available to dispatch Requests in a Service, Activity, Loader etc.

Now as far as the ImageLoader is concerned I would make a singleton class wrapping some functionality so you only have one instance of ImageCache and one ImageLoader, Ex.

publicclassImageLoaderHelper
{
    privatestaticImageLoaderHelpermInstance=null;

    privatefinal ImageLoader mImageLoader;
    privatefinal ImageCache mImageCache;

    publicstatic ImageLoaderHelper getInstance() {
        if(mInstance == null)
            mInstance = newImageLoaderHelper();
        return mInstance;
    }

    privateImageLoaderHelper() {
        mImageCache = newMyCustomImageCache();
        mImageLoader = newImageLoader(MyApplication.getVolleyQueue(),mImageCache);
    }

    // Now you can do what ever you want with your ImageCache and ImageLoader
}

If you want a really good example of ImageLoading with volley check out this sample project it is really useful.

Hope this helps.

Post a Comment for "Instantiating Core Volley Objects"