Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 instantiated in onCreate() but it doesn't seem to make sense to create a new request queue for each and every activity. I also have loads of activities and services and I will be using it everywhere. If I really do have to instantiate them in each Service or Activity, how expensive are they?

What is best practice production apps are using to instantiate and access these objects?

like image 725
Eurig Jones Avatar asked Jun 27 '13 06:06

Eurig Jones


1 Answers

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:

public class MyApplication extends Application
{
    private static RequestQueue mRequestQueue;

    @Override
    public void onCreate() {
        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.

public class ImageLoaderHelper
{
    private static ImageLoaderHelper mInstance = null;

    private final ImageLoader mImageLoader;
    private final ImageCache mImageCache;

    public static ImageLoaderHelper getInstance() {
        if(mInstance == null)
            mInstance = new ImageLoaderHelper();
        return mInstance;
    }

    private ImageLoaderHelper() {
        mImageCache = new MyCustomImageCache();
        mImageLoader = new ImageLoader(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.

like image 130
Brosa Avatar answered Nov 02 '22 07:11

Brosa