Junior — Middle
How to implement database creation using the Room library in Android?
sobes.tech AI
Answer from AI
To create a database using the Room library in Android, you need to follow several steps:
- Define entities — classes that will represent tables in the database. Each class field corresponds to a table column.
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "users")
data class User(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val name: String,
val age: Int
)
- Create DAO (Data Access Object) — an interface with methods for data access (insertion, update, deletion, queries).
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface UserDao {
@Insert
suspend fun insertUser(user: User)
@Query("SELECT * FROM users")
suspend fun getAllUsers(): List<User>
}
- Create a database class inheriting from RoomDatabase and declare entities and DAO in it.
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
- Initialize the database in the application using Room.databaseBuilder.
import androidx.room.Room
val db = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java, "app-database"
).build()
val userDao = db.userDao()
Thus, Room will automatically generate the necessary code to work with SQLite, providing convenient and safe data access.