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

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    private static Context mContext;

    private CookieManager cookieManager;

    @Override
    public void onCreate() {

        super.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;
    }


    /*** VOLLEY REQUEST MANAGER ***/

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            //set the server cookies, essential if your server require authentication
            cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
            CookieHandler.setDefault(cookieManager);
            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);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

}

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:

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