This tutorial aims to provide a comprehensive understanding of how to manage persistent data storage in Android using SQLite and Room Database. By the end of this tutorial, you will be proficient in creating a database, performing CRUD (Create, Read, Update, Delete) operations, and managing database versions and migrations.
SQLite is a lightweight database that is used for mobile app development in Android. However, using SQLite directly can be a bit cumbersome. To simplify the work, Android introduced the Room persistence library, an abstraction layer over SQLite.
To create a database using Room, you need to define an interface that extends RoomDatabase
. This interface is used as a database holder.
@Database(entities = [YourEntity::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun yourDao(): YourDao
}
In this code, YourEntity
is your data model class and YourDao
is an interface containing methods for database operations.
CRUD operations are performed using DAO (Data Access Object). DAO is an interface that defines all the database operations that you want to perform.
@Dao
interface YourDao {
@Query("SELECT * FROM yourEntity")
fun getAll(): List<YourEntity>
@Insert
fun insertAll(vararg yourEntity: YourEntity)
@Delete
fun delete(yourEntity: YourEntity)
}
Whenever you make a change in the database schema, you'll need to update the database version and provide a migration strategy.
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE YourEntity ADD COLUMN new_column INTEGER")
}
}
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "database-name"
).build()
val userDao = db.userDao()
val user = User(name = "John", age = 30)
userDao.insertAll(user)
val users = userDao.getAll()
for (user in users){
println(user.name)
}
In this tutorial, you've learned the basics of SQLite and Room Database, how to create a database, perform CRUD operations, and manage database versions and migrations.
For further learning, you can explore more complex queries and database relations in Room.
Create a Room Database for a blog app, where each article has a title, content, and author. Implement CRUD operations.
Implement a migration from version 1 to version 2 of your blog app, where you add a 'publishedDate' column to your article table.
Remember, practice is key to mastering any skill. Happy coding!