The Wayback Machine - https://web.archive.org/web/20240907003430/https://www.geeksforgeeks.org/how-to-use-singleton-pattern-for-room-database-in-android/
Open In App

How to Use Singleton Pattern for Room Database in Android?

Last Updated : 15 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite:

Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally. This is recommended by Google over SQLite Database although the SQLite APIs are more powerful they are fairly low-level, which requires a lot of time and effort to use. But Room makes everything easy and clear to create a Database and perform the operations on it. The singleton pattern is one of the simplest design patterns. Sometimes we need to have only one instance of our class for example a single DB connection shared by multiple objects as creating a separate DB connection for every object may be costly. Similarly, there can be a single configuration manager or error manager in an application that handles all problems instead of creating multiple managers. In short, we use the Singleton pattern when we need to instantiate a single instance of a class. We define a class in such a way that only one instance can be created.

Where can we use the Singleton pattern in Android development?

A few of the examples where we can use Singleton Pattern in Android are:

  • When we are using the Room database, We need only one instance of the Room Database class throughout the app. Having the number of instances of a Database can lead to memory leaks. Therefore we use the singleton patterns in the Database.
  • In MVVM architecture, When we are creating Repository, We only need one Instance as nothing changes in the Repository class throughout the execution of the app.

There are other situations as well where we prefer to use the Singleton pattern. In this article, we will focus on How to use the Singleton pattern in android. As we have got the idea behind using the Singleton pattern in the Database, Now we shall further move on for the implementation.

Implementation

Here, We will Implement the Room database(assuming a database to store contacts) using the Singleton pattern.

  • First, We will define the Data Entity.
  • It will be a data class, let’s give it a name Contact.kt

Refer to the below code for reference.

Kotlin




import androidx.room.Entity
import androidx.room.PrimaryKey
  
@Entity(tableName = "contact")
data class Contact(
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val name: String,
    val phoneNum: String
)


(autoGenerate = true) is used to auto-increment to id whenever a new data is added.

  • Then we need to create Dao.
  • Dao is an interface, So no need to define methods inside it. Room takes to care for implementation of these methods.
  • Dao is used to accessing the data object in the database.

Refer to the below code for reference.

Kotlin




import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
  
@Dao
interface ContactDao {
    @Insert
    fun insert(contact: Contact)
  
    @Query("Select * From contact")
    fun getContact():List<Contact>
}


  • Now we will create the database class, it is the main access point to the application’s persisted data.
  • It is an abstract class, It inherits the RoomDatabase. Here we implement the singleton pattern.

Refer to the below code for reference.

Kotlin




import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
  
@Database(entities = [Contact::class], version = 1)
abstract class ContactDatabase : RoomDatabase() {
    abstract fun contactDao(): ContactDao
  
    companion object {
        private var INSTANCE: ContactDatabase? = null
        fun getDatabase(context: Context): ContactDatabase {
            if (INSTANCE == null) {
                synchronized(this) {
                    INSTANCE =
                        Room.databaseBuilder(context,ContactDatabase::class.java, "contact_database")
                            .build()
                }
            }
            return INSTANCE!!
        }
    }
}


  • We have used a companion object to directly access the getDatabase( ) method while creating an instance of the Database class.
  • We have used a synchronized block to prevent multiple calls at a time from different threads.

So, this companion object is common whenever you want to use the Singleton pattern in the Room database.



Similar Reads

How to Perform CRUD Operations in Room Database in Android?
Data from the app can be saved on users' devices in different ways. We can store data in the user's device in SQLite tables, shared preferences, and many more ways. In this article, we will take a look at saving data, reading, updating, and deleting data in Room Database on Android. We will perform CRUD operations using Room Database on Android. In
15+ min read
Testing Room Database in Android using JUnit
In this article, we are going to test the Room Database in android. Here we are using JUnit to test our code. JUnit is a “Unit Testing” framework for Java Applications which is already included by default in android studio. It is an automation framework for Unit as well as UI Testing. It contains annotations such as @Test, @Before, @After, etc. Her
5 min read
How to Build a Simple Note Android App using MVVM and Room Database?
Android provides us a feature with which we can store users' data inside their mobile itself with different storage options such as Shared Preferences, SQLite database, and the Room Database. All the data storing techniques are having different use cases. In this article, we will specifically take a look at using a Room Database with Architecture C
15+ min read
Android SearchView in Room Database
SearchView in databases is a pretty basic functionality that you can see in most of the applications in your day-to-day life, then why not, you should learn and implement it. it is not too much complicated to implement in your application. There are a lot of easier ways that are how you can implement it. The tasks that you should use to implement f
12 min read
How to Prepopulate Room Database in Android?
Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally. This is recommended by Google over SQLite Database although the SQLite APIs are more powerful they are fairly low-level, which requires a lot of time and effort to use
3 min read
Android - Data Access Object in Room Database
Data Access Objects, or DAOs, are used in Room to access your application's persisted data. When compared to query builders or direct queries, they are a better and more modular way to access your database. You should also make a note that a DAO need not be only a class. If it's an abstract class, it can have a function Object() { [native code] } t
4 min read
How to Build a Simple Contact List Android App using MVVM and Room Database?
A contact list app is a great tool to store and manage our contacts in one place. With the rise of smartphones and mobile devices, contact list apps have become increasingly popular. In this article, we will explore the development of a contact list app using Kotlin, Room Database, and MVVM architecture. Model — View — ViewModel (MVVM) is the indus
7 min read
Room Database with Kotlin Coroutines in Android
This project will be used for the implementation phase. If you have not yet completed the project, you should do so and then return. To keep things simple, the project employs a basic MVVM architecture. The complete code for the implementation mentioned in this blog can be found in the project itself. First, we must configure the Room Database's de
3 min read
How to Build a Grocery Android App using MVVM and Room Database?
In this article, we are going to build a grocery application in android using android studio. Many times we forget to purchase things that we want to buy, after all, we can’t remember all the items, so with the help of this app, you can note down your grocery items that you are going to purchase, by doing this you can’t forget any items that you wa
15+ min read
Overview of Room in Android Architecture Components
Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally. This is recommended by Google over SQLite Database although the SQLite APIs are more powerful they are fairly low-level, which requires a lot of time and effort to use
5 min read
Android Room Persistence Library in Kotlin
Android Room Persistence Library is one of the sets of libraries provided by Android Jetpack so as to help developers follow the best practices while eliminating boilerplate codes and reducing fragmentation. In Android applications, we often need to store structured data, and persisting that data locally is always a good idea. This way if our appli
5 min read
Android - Entity Relationship in Room
This article describes how to define the relationship between entities in the Room persistence library. Because SQLite is a relational database, entities can be related to one another. Entities in Room cannot directly reference other entities because doing so may result in the loading of unnecessary data every time. Even so, you may want to refer t
6 min read
Introduction to Room Persistent Library in Android
Room is a persistence library for Android that is part of Google's Android Jetpack project. According to the documentation, Room acts as an abstraction layer over SQLite, allowing for fluent database access while leveraging SQLite's full power. Apps that deal with a large amount of structured data can benefit greatly from storing it locally. The mo
4 min read
How Room Works Internally in Android?
Room autogenerates implementations of your @Database and @Dao annotated classes the first time you compile your code after creating a Room Database. The implementation of UserDatabase and UserDao in the preceding example is generated automatically by the Room annotation processor. The autogenerated code can be found in the build/generated/source/ka
5 min read
How to Use Room with LiveData?
In previous articles, we discussed how to use the Room persistence library in Android applications and how Room works internally. We also talked about the various operations we can perform with the help of Room. One of them is using LiveData with Room. The room allows for the simple integration of LiveData. You only need to return LiveData from you
5 min read
Singleton Class in Android
The Singleton Pattern is a software design pattern that restricts the instantiation of a class to just "one" instance. It is used in Android Applications when an item needs to be created just once and used across the board. The main reason for this is that repeatedly creating these objects, uses up system resources. The identical object should ther
4 min read
Singleton Class in Kotlin
Singleton Class in Kotlin is also called as the Singleton Object in Kotlin. Singleton class is a class that is defined in such a way that only one instance of the class can be created and used everywhere. Many times we create the two different objects of the same class, but we have to remember that creating two different objects also requires the a
4 min read
How to Use Firebase Firestore as a Realtime Database in Android?
Firebase Firestore is the backend database that is used to add, read, update and delete data from Android. But in Firebase Firestore there is a separate method that is used to read data from Firebase Firestore in Realtime Database. In this article, we will read data from Firebase Firestore in Realtime Database. Note that we are going to implement t
6 min read
How to Use Stack Overflow to Fix Errors During Android App Development in Android Studio?
Stack Overflow, the life savior of developers, feels like Stack Overflow is built for the developers, by the developers, of the developers. According to Wikipedia: "Stack Overflow is a question-and-answer site for professional and enthusiast programmers". So being a developer or programmer can you imagine your life without Stack Overflowâ€Ķ. ? Most p
4 min read
How to Use Fast Android Networking Library in Android with Example?
In Android, we know multiple networking libraries like Retrofit, Volley. We use these libraries specifically for making networking requests like performing actions on API. But Besides that, there is another library called Fast Networking Library which has a few advantages over other libraries. In this tutorial, we will be specifically focusing on l
4 min read
How to Use Android Sliding Activity Library in Android App?
Sliding activities allow you to easily set header content, menus, and data onto slidable screens. Easily create activities that can slide vertically on the screen and fit well into the material design age. We can set header images to our sliding activity. We can also customize the color that will affect the header and the status bar. We can also di
3 min read
How to Update Data to SQLite Database in Android?
We have seen How to Create and Add Data to SQLite Database in Android as well as How to Read Data from SQLite Database in Android. We have performed different SQL queries for reading and writing our data to SQLite database. In this article, we will take a look at updating data to SQLite database in Android. What we are going to build in this articl
10 min read
How to Build a TODO Android Application with AWS DynamoDB as Database?
This is a TODO application made on android studio IDE, code is written in JAVA, and data store in AWS DynamoDB and fetch to the home screen. The connection established between the application and AWS through Amplify CLI and the data is successful gets stored by creating a TODO Table in DynamoDB, a Schema is also created which shows the structure of
7 min read
How to Install and Add Data to Realm Database in Android?
Realm Database is a service which is provided by MongoDb which is used to store data in users device locally. With the help of this data can be stored easily in users' devices and can be accessed easily. We can use this database to store data in the user's device itself. This is a series of 4 articles in which we are going to perform the basic CRUD
8 min read
How to Access SQLite Database in Android For Debugging?
A software library that provides a relational database management system is called SQLite. It allows the users to interact with RDBMS. The lite in SQLite denotes the lightweight when it comes to setup, database administration, and resources required. In SQLite, a database is stored in a single file — a property that differentiates it from other dat
10 min read
Different Ways to View Contents of Database File in Android Studio
Data is a group of information and it can be any kind of information - text, numbers, image, video. An organized collection of this data is called a Database. It is made so that the data can be accessed and managed easily. Data can be organized into tables, rows, columns as that make it easier to handle the data. The main purpose of having a databa
4 min read
How to Save Data to the Firebase Realtime Database in Android?
Firebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simple app in which we will be adding our Data to Fire
9 min read
How to Retrieve Data from the Firebase Realtime Database in Android?
Firebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous is for its Firebase Realtime Database. By using Firebase Realtime Database
7 min read
How to Update Data in Back4App Database in Android?
In the previous article, we have seen adding as well as reading data from our Bac4App database in the Android app. In this article, we will take a look at Updating this data in your database. What we are going to build in this article? We will be building a simple application in which we will be updating the previously added data in our Back4App da
7 min read
How to Read Data from Back4App Database in Android?
We have seen adding data to the Back4App database in the Android app. In this article, we will take a look at reading this data from our database in our Android App. What we are going to build in this article? We will be creating a new screen in the previous application and inside that, we will display our data which we added inside our Back4App Da
9 min read
Article Tags :