Click here to Skip to main content
15,868,101 members
Articles / Mobile Apps / Android
Tip/Trick

Simple Singleton Pattern in Android

Rate me:
Please Sign up or sign in to vote.
4.33/5 (10 votes)
29 Nov 2015CPOL1 min read 36.1K   361   5   4
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

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
<!--?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
    <!--?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

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

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Pakistan Pakistan
Studying Computer Science at PAF-KIET.

Comments and Discussions

 
QuestionDo you really need it? Pin
haker046-Dec-15 21:03
haker046-Dec-15 21:03 
AnswerRe: Do you really need it? Pin
Kamran_Shahid6-Dec-15 22:38
professionalKamran_Shahid6-Dec-15 22:38 
GeneralWell explained Pin
Asadullah Maher1-Dec-15 10:39
Asadullah Maher1-Dec-15 10:39 
GeneralMy vote of 5 Pin
Tahir Nisar1-Dec-15 9:05
Tahir Nisar1-Dec-15 9:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.