NoobsPlanet

Register a free account today to become a member! Once signed in, you'll be able to participate on this site by adding your own topics, posts and unlimited download to our resources, as well as connect with other members through your own private inbox!

Volley SingleTon Class

noobsplanet

Well-known member
Staff member
Administrator
Moderator
You should consider using a volley SingleTon when your application makes a constant use of your network.It is most efficient to set up a single instance of RequestQueue that will last the lifetime of your app that you can achieve in many ways but the recommended approach is to implement a singleton class that encapsulates RequestQueue and other Volley functionality.
RequestQueue must be instantiated with the Application context, not an Activity context. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device in landscape mode or vice versa).

The following is how you can create a singleton class, Create a class name called MySingleton.java and paste the following code into class, then press ALT + Enter on class name and import package. Now, You can add volley to request queue from any class just by the single line.
MySingleton.getInstance(this).addToRequestQueue(requestQueue);.


MySingleton.java:
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private static Context mContext;

    private MySingleton(Context context){
        // Specify the application context
        mContext = context;
        // Get the request queue
        mRequestQueue = getRequestQueue();
    }

    public static synchronized MySingleton getInstance(Context context){
        // If Instance is null then initialize new Instance
        if(mInstance == null){
            mInstance = new MySingleton(context);
        }
        // Return MySingleton new Instance
        return mInstance;
    }

    public RequestQueue getRequestQueue(){
        // If RequestQueue is null the initialize new RequestQueue
        if(mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
        }

        // Return RequestQueue
        return mRequestQueue;
    }

    public<T> void addToRequestQueue(Request<T> request){
        // Add the specified request to the request queue
        getRequestQueue().add(request);
    }
}
 
Last edited:

shan de

New member
I still dont understand why we need single object from Singlton class and what is the advantage of that? Could you please give me a simple example.
 
Top