An app with implementation of Room database for Android platform

Related tags

O/R Mapping RoomRoom
Overview

Room Room

An app with implementation of Room database for Android platform

The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In particular, Room provides the following benefits:

  • Compile-time verification of SQL queries.
  • Convenience annotations that minimize repetitive and error-prone boilerplate code.
  • Streamlined database migration paths.

To persist data with Room database you just need:

1. Add Room dependencies (build.gradle)

plugins {  
  id 'kotlin-android-extensions'  
  id 'kotlin-kapt'  
}

dependencies {  
  def roomVersion = "2.4.1"  
  implementation "androidx.room:room-runtime:$roomVersion"  
  kapt "androidx.room:room-compiler:$roomVersion"
}

2. Create your Entity

@Entity   
data class User(  
  @PrimaryKey(autoGenerate = true) val uid: Int? = 0,  
  @ColumnInfo(name = "first_name") val firstName: String?,  
  @ColumnInfo(name = "last_name") val lastName: String?  
)

3. Declare your data access object

@Dao  
interface UserDao {  
    @Query("SELECT * FROM user")  
    fun getAll(): List<User>  
  
    @Query("SELECT * FROM user WHERE uid IN (:userIds)")  
    fun loadAllByIds(userIds: IntArray): List<User>  
  
    @Query("SELECT * FROM user WHERE first_name LIKE :first AND " +  
            "last_name LIKE :last LIMIT 1")  
    fun findByName(first: String, last: String): User  
  
    @Insert(onConflict = OnConflictStrategy.REPLACE)  
    fun insertAll(vararg users: User)  
  
    @Update
    fun updateUser(user: User)  
  
    @Delete  
	fun delete(user: User)  
}

We use a singleton pattern to call our database when needed. Since we are not using LiveData or Coroutines scopes, we need to use .allowMainThreadQueries(). Keep in mind that this approach is not the best answer

4. App database singleton

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

	companion object {  
        private var INSTANCE: AppDatabase? = null
		fun getDatabase(context: Context): AppDatabase {  
			if (INSTANCE == null) {
					synchronized(this) {  
						INSTANCE = Room.databaseBuilder(  
	                        context,  
							AppDatabase::class.java, "user_database")  
                            .allowMainThreadQueries()  
                            .build()
                    }  
			}  
            return INSTANCE!!  
        }  
    }  
}

Everything is ready, now just call our singleton and start to use

5. Start your queries

val db = AppDatabase.getDatabase(requireContext())  
val userDao = db.userDao()

val myUser = (null, "Void", "Hash")
userDao.insertAll(myUser)
userDao.updateUser(myUser)
userDao.getAll()
userDao.delete(myUser)

A piece of cake! Now, have fun!

You might also like...
android 数据库框架,sqlite database

DBExecutor 主要的功能 1.使用了读写锁,支持多线程操作数据。 2.支持事务 3.支持ORM 4.缓存Sql,缓存表结构 这个类库主要用于android 数据库操作。 始终围绕着一个类对应一个表的概念。 只要创建一个实体类,就不用当心它怎么存储在数据库中,不用重新写增删改查的代码。基本的功

LiteOrm is a fast, small, powerful ORM framework for Android. LiteOrm makes you do CRUD operarions on SQLite database with a sigle line of code efficiently.

#LiteOrm:Android高性能数据库框架 A fast, small, powerful ORM framework for Android. LiteOrm makes you do CRUD operarions on SQLite database with a sigle line

An Android library that makes developers use SQLite database extremely easy.

LitePal for Android 中文文档 LitePal is an open source Android library that allows developers to use SQLite database extremely easy. You can finish most o

a 3d database ORM experiment. (used in two commercial projects)

Android-TriOrm a 3d database ORM experiment for Android. (used in two commercial projects). based around small tables concept and JVM Serialization. H

Realm is a mobile database: a replacement for SQLite & ORMs

Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the Java version of Realm

Collection of Kotlin APIs/tools to make using Realm Mobile database easier

Compass Kotlin API and tools to make working with Realm easier Components Compass is designed to make working with Realm easier through collection of

Starter code for Android Kotlin Fundamentals Codelab 6.1 Room

TrackMySleepQuality - Starter Code Starter code for Android Kotlin Fundamentals Codelab 6.1 Room Introduction TrackMySleepQuality is an app for record

Android Room with a View - Java

Android Room with a View - Java This code used Room in a database-backed app. You'll create the data layer for an app that tracks Product, and you'll

Exercicio praticando o SQLite, Room e Flow

Bus Scheduler App This folder contains the source code for the Bus Scheduler app codelab. Introduction The Bus Scheduler app displays a list of bus st

Owner
Void Hash
Void Hash
A blazing fast, powerful, and very simple ORM android database library that writes database code for you.

README DBFlow is fast, efficient, and feature-rich Kotlin database library built on SQLite for Android. DBFlow utilizes annotation processing to gener

Andrew Grosner 4.9k Dec 30, 2022
Room Database Queries with Kotlin Flow

Room Database Queries with Flow This app displays a list of bus stops and arrival times. Tapping a bus stop on the first screen will display a list of

asifj96 0 Apr 26, 2022
Implementation of MVVM , Live Data and Room DAO for a robust materialistic design

Someday App to manage Weekly tasks Because who needs to remind you every week to do Samething Preview Main Layout Light Dark Main Layout (Expanded) Li

Anshul Saraf 2 May 13, 2021
A simple ToDo app to demonstrate the use of Realm Database in android to perform some basic CRUD operations like Create, Update and Delete.

Creating a Realm Model Class @RealmClass open class Note() : RealmModel { @PrimaryKey var id: String = "" @Required var title: String

Joel Kanyi 15 Dec 18, 2022
Insanely easy way to work with Android Database.

Sugar ORM Insanely easy way to work with Android databases. Official documentation can be found here - Check some examples below. The example applicat

null 2.6k Dec 16, 2022
An Android library that makes developers use SQLite database extremely easy.

LitePal for Android 中文文档 LitePal is an open source Android library that allows developers to use SQLite database extremely easy. You can finish most o

Lin Guo 7.9k Dec 31, 2022
Insanely easy way to work with Android Database.

Sugar ORM Insanely easy way to work with Android databases. Official documentation can be found here - Check some examples below. The example applicat

null 2.6k Jan 9, 2023
An Android helper class to manage database creation and version management using an application's raw asset files

THIS PROJECT IS NO LONGER MAINTAINED Android SQLiteAssetHelper An Android helper class to manage database creation and version management using an app

Jeff Gilfelt 2.2k Dec 23, 2022
SquiDB is a SQLite database library for Android and iOS

Most ongoing development is currently taking place on the dev_4.0 branch. Click here to see the latest changes and try out the 4.0 beta. Introducing S

Yahoo 1.3k Dec 26, 2022
Compile time processed, annotation driven, no reflection SQLite database layer for Android

SqliteMagic Simple yet powerful SQLite database layer for Android that makes database handling feel like magic. Overview: Simple, intuitive & typesafe

Siim Kinks 118 Dec 22, 2022