0
0
Android Kotlinmobile~5 mins

Entity, DAO, Database classes in Android Kotlin

Choose your learning style9 modes available
Introduction

These classes help your app save and get data easily. They organize how data is stored and used.

When you want to save user info like names or scores.
When your app needs to remember settings or preferences.
When you want to keep a list of items like tasks or notes.
When you need to update or delete saved data.
When you want to load data quickly without internet.
Syntax
Android Kotlin
1. Entity class: Defines a table in the database.

@Entity(tableName = "users")
data class User(
  @PrimaryKey val id: Int,
  val name: String
)

2. DAO interface: Defines methods to access the database.

@Dao
interface UserDao {
  @Insert
  suspend fun insert(user: User)

  @Query("SELECT * FROM users")
  suspend fun getAll(): List<User>
}

3. Database class: Holds the database and connects DAO.

@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
  abstract fun userDao(): UserDao
}

Entity: Represents a table with columns.

DAO: Contains functions to add, read, update, or delete data.

Database: The main access point to your stored data.

Examples
This creates a table named 'tasks' with two columns: taskId and description.
Android Kotlin
@Entity(tableName = "tasks")
data class Task(
  @PrimaryKey val taskId: Int,
  val description: String
)
This DAO lets you add a task and get all tasks from the database.
Android Kotlin
@Dao
interface TaskDao {
  @Insert
  suspend fun addTask(task: Task)

  @Query("SELECT * FROM tasks")
  suspend fun getTasks(): List<Task>
}
This database class connects the Task entity and TaskDao for use in the app.
Android Kotlin
@Database(entities = [Task::class], version = 1)
abstract class TaskDatabase : RoomDatabase() {
  abstract fun taskDao(): TaskDao
}
Sample App

This program creates an in-memory database, adds two users, and prints them.

Android Kotlin
import androidx.room.*
import android.content.Context
import kotlinx.coroutines.runBlocking

@Entity(tableName = "users")
data class User(
  @PrimaryKey val id: Int,
  val name: String
)

@Dao
interface UserDao {
  @Insert
  suspend fun insert(user: User)

  @Query("SELECT * FROM users")
  suspend fun getAll(): List<User>
}

@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
  abstract fun userDao(): UserDao
}

fun main() {
  // Normally, you get context from Android app, here we simulate
  val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<Context>()
  val db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
    .allowMainThreadQueries()
    .build()
  val userDao = db.userDao()

  runBlocking {
    userDao.insert(User(1, "Alice"))
    userDao.insert(User(2, "Bob"))
    val users = userDao.getAll()
    users.forEach { println("User: ${it.id} - ${it.name}") }
  }
}
OutputSuccess
Important Notes

Use @PrimaryKey to mark the unique ID for each entity.

DAO methods can be suspend functions to work with Kotlin coroutines for smooth background tasks.

Database class must be abstract and extend RoomDatabase.

Summary

Entity defines the data table structure.

DAO provides methods to access and modify data.

Database connects entities and DAOs for app use.