Sobes.tech
Junior — Middle

What methods and tools do you use to interact with the database?

sobes.tech AI

Answer from AI

The most commonly used methods and tools for interacting with a database in Android are:

  • SQLite — an embedded relational database. You can use the SQLiteOpenHelper class to work with it.
  • Room — a library from Google that simplifies working with SQLite by providing a convenient ORM layer and support for annotations.
  • ContentProvider — for data sharing between applications.
  • Realm or ObjectBox — alternative NoSQL databases for mobile applications.

Example of using Room:

@Entity
data class User(
    @PrimaryKey val id: Int,
    val name: String
)

@Dao
interface UserDao {
    @Query("SELECT * FROM user")
    fun getAll(): List<User>

    @Insert
    fun insert(user: User)
}

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

// Initialization
val db = Room.databaseBuilder(
    context,
    AppDatabase::class.java, "database-name"
).build()

// Usage
val users = db.userDao().getAll()