1. Introduction
Data management is an essential element in modern application development. The database for storing user information or the state of the application is becoming increasingly important. In Android applications, the use of databases is essential for effectively managing user data. In this course, we will cover how to store data in a database using Kotlin.
2. Types of Databases
There are various databases that can be used in Android, among which the most commonly used are as follows:
- SQLite: A lightweight database built into the Android platform that uses SQL language to manage data.
- Room: A wrapper library for SQLite, allowing interaction with SQLite in an object-oriented manner.
- Firebase Realtime Database: A cloud-based database by Google that provides real-time data synchronization and offline support.
This course will focus on SQLite and Room.
3. SQLite Database
SQLite is a simple and efficient way to store data locally. It allows for quick access to requested data in component-based Android applications. To use the SQLite database, the following key steps must be followed.
3.1. SQLiteOpenHelper Class
SQLiteOpenHelper is a class for creating and managing database versions. It helps manage the database.
Below is a simple implementation example of SQLiteOpenHelper:
class MyDatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
val createTableSQL = "CREATE TABLE ${TABLE_NAME} (" +
"${COLUMN_ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
"${COLUMN_NAME} TEXT)"
db.execSQL(createTableSQL)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
onCreate(db)
}
}
3.2. Inserting, Retrieving, Updating, and Deleting Data
Now, let’s learn how to insert, read, update, and delete data in the database.
Inserting Data
fun insertData(name: String) {
val db = this.writableDatabase
val values = ContentValues().apply {
put(COLUMN_NAME, name)
}
db.insert(TABLE_NAME, null, values)
db.close()
}
Retrieving Data
fun getData(): List {
val dataList = mutableListOf()
val db = this.readableDatabase
val cursor: Cursor = db.rawQuery("SELECT * FROM $TABLE_NAME", null)
if (cursor.moveToFirst()) {
do {
val name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME))
dataList.add(name)
} while (cursor.moveToNext())
}
cursor.close()
db.close()
return dataList
}
Updating Data
fun updateData(id: Int, newName: String) {
val db = this.writableDatabase
val values = ContentValues().apply {
put(COLUMN_NAME, newName)
}
db.update(TABLE_NAME, values, "$COLUMN_ID = ?", arrayOf(id.toString()))
db.close()
}
Deleting Data
fun deleteData(id: Int) {
val db = this.writableDatabase
db.delete(TABLE_NAME, "$COLUMN_ID = ?", arrayOf(id.toString()))
db.close()
}
4. Room Database
Room is a library that provides a simpler and more flexible way to access databases. It reduces the amount of database-related code and helps to use the database more safely. Room consists of three main components:
- Entity: Represents a table in the database.
- DAO (Data Access Object): Defines methods for accessing the database.
- Database: The Room database class.
4.1. Defining Entity Classes
Defining an Entity in Room is akin to designing a table. Below is a simple example of a User Entity:
@Entity(tableName = "user_table")
data class User(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "name") val name: String
)
4.2. Defining DAO Interfaces
DAO defines methods to perform CRUD (Create, Read, Update, Delete) operations on the database:
@Dao
interface UserDao {
@Insert
suspend fun insert(user: User)
@Query("SELECT * FROM user_table")
suspend fun getAllUsers(): List
@Update
suspend fun update(user: User)
@Delete
suspend fun delete(user: User)
}
4.3. Defining RoomDatabase Class
The RoomDatabase class allows for the instantiation of DAO and the creation of the database:
@Database(entities = [User::class], version = 1)
abstract class UserDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
@Volatile
private var INSTANCE: UserDatabase? = null
fun getDatabase(context: Context): UserDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
UserDatabase::class.java,
"user_database"
).build()
INSTANCE = instance
instance
}
}
}
}
4.4. Manipulating Data
Using the Room database, here’s how you can insert, retrieve, update, and delete data:
Inserting Data
private fun insertUser(user: User) {
CoroutineScope(Dispatchers.IO).launch {
val db = UserDatabase.getDatabase(context)
db.userDao().insert(user)
}
}
Retrieving Data
private fun getAllUsers() {
CoroutineScope(Dispatchers.IO).launch {
val db = UserDatabase.getDatabase(context)
val users = db.userDao().getAllUsers()
}
}
Updating Data
private fun updateUser(user: User) {
CoroutineScope(Dispatchers.IO).launch {
val db = UserDatabase.getDatabase(context)
db.userDao().update(user)
}
}
Deleting Data
private fun deleteUser(user: User) {
CoroutineScope(Dispatchers.IO).launch {
val db = UserDatabase.getDatabase(context)
db.userDao().delete(user)
}
}
5. Conclusion
In this course, we learned how to utilize databases in Android apps using Kotlin. We understood the advantages and disadvantages of both SQLite and Room, and learned how to store and manage data in an application through concrete implementation examples. Now, we hope you can use these techniques to effectively manage user data and enhance the functionality of your app.