65.9K
CodeProject is changing. Read more.
Home

Simple Singleton Pattern in Android

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (10 votes)

Nov 29, 2015

CPOL

1 min read

viewsIcon

36954

downloadIcon

362

Singleton pattern implementation in Android

You can download the complete source code (Android Studio 1.4 - Target SDK: 23) from the links below:

Introduction

Singleton is the most common, simple pattern to learn and implement. A singleton class has only one instance and it can be accessed from anywhere in our program. It can be used when we need our object to store sessions, database connections, communication protocols, etc. 

Background

We will create a simple application which will store username from login activity and print the message "Welcome [Your Name]" on welcome activity. The idea is to use a single class instance to store and get username in two different classes. We will be ignoring username and password check, as the example is focus on the basic concept of singleton class.

Using the Code

Our singleton class will store the username. Usually in real scenarios username is stored as sessions, so we are calling it "SingletonSession.java".

SingletonSession.java

    public class SingletonSession {

    private static SingletonSession instance;
    private String username;
    //no outer class can initialize this class's object
    private SingletonSession() {}

    public static SingletonSession Instance()
    {
        //if no instance is initialized yet then create new instance
        //else return stored instance
        if (instance == null)
        {
            instance = new SingletonSession();
        }
        return instance;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

As we are using 2 activities, LoginActivity and WelcomeActivity, we will be having 2 layouts activity_login.xml and activity_welcome.xml.

activity_login.xml

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout android:layout_height="match_parent" android:layout_width="match_parent" 
android:orientation="vertical" tools:context=".LoginActivity" 
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools">

    <textview android:id="@+id/textView" android:layout_gravity="center_horizontal" 
    android:layout_height="wrap_content" android:layout_width="wrap_content" 
    android:text="Login Form" android:textappearance="?android:attr/textAppearanceLarge">

    <edittext android:hint="Your Username" android:id="@+id/editUsername" 
    android:layout_height="wrap_content" android:layout_width="match_parent">

    <edittext android:hint="Your Password" android:id="@+id/editPassword" 
    android:inputtype="textPassword" android:layout_height="wrap_content" 
    android:layout_width="match_parent"><button android:id="@+id/btnLogin" 
    android:layout_gravity="center_horizontal" 
android:layout_height="wrap_content" 
android:layout_width="wrap_content" android:text="Login">
</button></edittext></edittext></textview></linearlayout>

activity_welcome.xml

    <!--?xml version="1.0" encoding="utf-8"?-->
<relativelayout android:layout_height="match_parent" android:layout_width="match_parent" 
tools:context="kamranshahid.singletonimplementation.WelcomeActivity" 
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools">

    <textview android:gravity="center" 
    android:id="@+id/txtWelcome" android:layout_height="fill_parent" 
    android:layout_width="fill_parent" android:text="Welcome" 
    android:textappearance="?android:attr/textAppearanceLarge">

</textview></relativelayout>    

Now implementing our SingletonSession within our LoginActivity.java and WelcomeActivity.java classes:

LoginActivity.java

    public class LoginActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Button btnLogin = (Button) findViewById(R.id.btnLogin);
        final EditText editUsername  = (EditText) findViewById(R.id.editUsername);

        btnLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // On login button click, storing our username into singleton class.
                SingletonSession.Instance().setUsername(editUsername.getText().toString());

                Intent welcomeActivity = new Intent(LoginActivity.this, WelcomeActivity.class);
                startActivity(welcomeActivity);
            }
        });
    }
}

In LoginActivity.java, we got the Instance of SingleSession class which is our Singleton class to setUsername() from our login activity.
As you notice, it is the first time we are calling SingletonSession and the class has no instance currently. It will create an instance and return. 

WelcomeActivity.java

    public class WelcomeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        TextView txtWelcome  = (TextView) findViewById(R.id.txtWelcome);

        //Displaying our username using singleton class.
        txtWelcome.setText("Welcome\n" + SingletonSession.Instance().getUsername());
    }
}

In WelcomeActivity.java, we again called SingletonSession class, but this time it will return the same instance we created at LoginActivity.java, hence we will get and show the username we set in LoginActivity here.

Output