Creating a Singleton in Android

In Android, creating a singleton to manage your http volley request, your cookies, your session, social logins or location updates is quite simple and can be very useful, especially if you are using volley library to make api requests.

To do so, create a new class, call it AppController and make it extends `Application`. Then copy paste the following code:

public class AppController extends Application  {

    public static final String TAG = AppController.class

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    private static Context mContext;

    private CookieManager cookieManager;

    public void onCreate() {


        mInstance = this; //return the singleton
        mContext = getApplicationContext();
        appName = mContext.getResources().getString(R.string.app_name);


    public CookieManager getCookieManager() {
        return cookieManager;

    public static SessionManager getSession() { 
        return mSession; 

    public static synchronized AppController getInstance() {
        return mInstance;

    public static Context getContext() {
        return mContext;


    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            //set the server cookies, essential if your server require authentication
            cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());

        return mRequestQueue;

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

    public <T> void addToRequestQueue(Request<T> req) {

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {


This class now handles all the volley requests and cookie management (you can see it in action in the tutorial Implementing a RESTful API Wrapper in Android (Part II)).

Finally, you just have to point your application to this class in your manifest to start using it:

        android:name=".utils.AppController" //change `.utils.` to your file's path