Как подключить room android studio
Completing the CAPTCHA proves you are a human and gives you temporary access to the web property.
What can I do to prevent this in the future?
If you are on a personal connection, like at home, you can run an anti-virus scan on your device to make sure it is not infected with malware.
If you are at an office or shared network, you can ask the network administrator to run a scan across the network looking for misconfigured or infected devices.
Another way to prevent getting this page in the future is to use Privacy Pass. You may need to download version 2.0 now from the Chrome Web Store.
Cloudflare Ray ID: 71aecefb2adb40db • Your IP : 82.102.23.104 • Performance & security by Cloudflare
Using Room Database | Android Jetpack in Android Apps
The Room persistence library it is an abstraction layer over SQLite.
The room is an ORM (object relational mapper) for SQLite database in Android. It is part of the Architecture Components released by Google.
Room is now considered as a better approach for data persistence than SQLiteDatabase. It makes it easier to work with SQLiteDatabase objects in your app, decreasing the amount of boilerplate code and verifying SQL queries at compile time.
Why use Room?
- Compile-time verification of SQL queries. each @Query and @Entity is checked at the compile time, that preserves your app from crash issues at runtime and not only it checks the only syntax, but also missing tables.
- Boilerplate code
- Easily integrated with other Architecture components (like LiveData)
Room vs SQLite
Room is an ORM, Object Relational Mapping library. In other words, Room will map our database objects to Java objects. Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
Difference between SQLite and Room persistence library:-
- In the case of SQLite, There is no compile-time verification of raw SQLite queries. But in Room, there is SQL validation at compile time.
- You need to use lots of boilerplate code to convert between SQL queries and Java data objects. But, Room maps our database objects to Java Object without boilerplate code.
- As your schema changes, you need to update the affected SQL queries manually. Room solves this problem.
- Room is built to work with LiveData and RxJava for data observation, while SQLite does not.
Components of Room DB:
Room has three main components of Room DB :
- Entity
- Dao
- Database
- Entity:
Represents a table within the database.Room creates a table for each class that has @Entity annotation, the fields in the class correspond to columns in the table. Therefore, the entity classes tend to be small model classes that don’t contain any logic.
Entities annotations
Before we get started with modeling our entities, we need to know some useful annotations and their attributes.
@Entity — every model class with this annotation will have a mapping table in DB
- foreignKeys — names of foreign keys
- indices — list of indicates on the table
- primaryKeys — names of entity primary keys
- tableName
@PrimaryKey — as its name indicates, this annotation points the primary key of the entity. autoGenerate — if set to true, then SQLite will be generating a unique id for the column
@ColumnInfo — allows specifying custom information about column
@Ignore — field will not be persisted by Room
@Embeded — nested fields can be referenced directly in the SQL queries.
2. Dao
DAOs are responsible for defining the methods that access the database. In the initial SQLite, we use the Cursor objects. With Room, we don’t need all the Cursor related code and can simply define our queries using annotations in the Dao class.
3. Database
Contains the database holder and serves as the main access point for the underlying connection to your app’s persisted, relational data.
To create a database we need to define an abstract class that extends RoomDatabase . This class is annotated with @Database , lists the entities contained in the database, and the DAOs which access them.
The class that’s annotated with @Database should satisfy the following conditions:
- Be an abstract class that extends RoomDatabase .
- Include the list of entities associated with the database within the annotation.
- Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao .
At runtime, you can acquire an instance of Database by calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder() .
Alright! So far so good!! Let’s implement it with an example.
Step 1: Create a new project in Android Studio with empty activity.
Step 2: Add dependencies
And then add below dependencies to app/build.gradle file:
Step 3: Create a Model Class
Now, let’s create an Entity called Person.
- It is must to declare one field as primary key. You need to annotate a field with @PrimaryKey with attribute autoGenerate by default it is false
- The class is annotated with @Entity and name of the table.
Step 4: Create Data Access Objects (DAOs)
DAOs are responsible for defining the methods that access the database.
To create a DAO we need to create an interface and annotated with @Dao.
— There are four annotations @Query, @Insert, @Update, @Delete to perform CRUD operations. @Query annotation is used to perform read operation on the database.
Step 5: Create the database
To create a database we need to define an abstract class that extends RoomDatabase . This class is annotated with @Database , lists the entities contained in the database, and the DAOs which access them.
Step 6: Managing Data
To manage the data, first of all, we need to create an instance of the database.
then we can insert delete and update the database.
Make sure all the operation should execute on a different thread.
Save data in a local database using Room Part of Android Jetpack.
Apps that handle non-trivial amounts of structured data can benefit greatly from persisting that data locally. The most common use case is to cache relevant pieces of data so that when the device cannot access the network, the user can still browse that content while they are offline.
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.
Because of these considerations, we highly recommend that you use Room instead of using the SQLite APIs directly.
Setup
To use Room in your app, add the following dependencies to your app's build.gradle file:
Groovy
Kotlin
Primary components
There are three major components in Room:
- The database class that holds the database and serves as the main access point for the underlying connection to your app's persisted data. that represent tables in your app's database. that provide methods that your app can use to query, update, insert, and delete data in the database.
The database class provides your app with instances of the DAOs associated with that database. In turn, the app can use the DAOs to retrieve data from the database as instances of the associated data entity objects. The app can also use the defined data entities to update rows from the corresponding tables, or to create new rows for insertion. Figure 1 illustrates the relationship between the different components of Room.
Figure 1. Diagram of Room library architecture.
Sample implementation
This section presents an example implementation of a Room database with a single data entity and a single DAO.
Data entity
The following code defines a User data entity. Each instance of User represents a row in a user table in the app's database.
Kotlin
To learn more about data entities in Room, see Defining data using Room entities.
Data access object (DAO)
The following code defines a DAO called UserDao . UserDao provides the methods that the rest of the app uses to interact with data in the user table.
Kotlin
Database
The following code defines an AppDatabase class to hold the database. AppDatabase defines the database configuration and serves as the app's main access point to the persisted data. The database class must satisfy the following conditions:
- The class must be annotated with a @Database annotation that includes an entities array that lists all of the data entities associated with the database.
- The class must be an abstract class that extends RoomDatabase .
- For each DAO class that is associated with the database, the database class must define an abstract method that has zero arguments and returns an instance of the DAO class.
Kotlin
Note: If your app runs in a single process, you should follow the singleton design pattern when instantiating an AppDatabase object. Each RoomDatabase instance is fairly expensive, and you rarely need access to multiple instances within a single process.
If your app runs in multiple processes, include enableMultiInstanceInvalidation() in your database builder invocation. That way, when you have an instance of AppDatabase in each process, you can invalidate the shared database file in one process, and this invalidation automatically propagates to the instances of AppDatabase within other processes.
Usage
After you have defined the data entity, the DAO, and the database object, you can use the following code to create an instance of the database:
Kotlin
You can then use the abstract methods from the AppDatabase to get an instance of the DAO. In turn, you can use the methods from the DAO instance to interact with the database:
Kotlin
Additional resources
To learn more about Room, see the following additional resources:
Samples
Codelabs
- Android Room with a View (Java)(Kotlin)
Blogs
- 7 Pro-tips for Room
- Incrementally migrate from SQLite to Room
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
7 шагов к использованию Room. Пошаговое руководство по миграции приложения на Room

Room — это библиотека, которая является частью архитектурных компонентов Android. Она облегчает работу с объектами SQLiteDatabase в приложении, уменьшая объём стандартного кода и проверяя SQL-запросы во время компиляции.
У вас уже есть Android-проект, который использует SQLite для хранения данных? Если это так, то вы можете мигрировать его на Room. Давайте посмотрим, как взять уже существующий проект и отрефакторить его для использования Room за 7 простых шагов.
В нашем примере приложения для миграции мы работаем с объектами типа User . Мы использовали product flavors для демонстрации различных реализаций уровня данных:
- sqlite — использует SQLiteOpenHelper и традиционные интерфейсы SQLite.
- room — заменяет реализацию на Room и обеспечивает миграцию.
Каждый вариант использует один и тот же слой пользовательского интерфейса, который работает с классом UserRepository благодаря паттерну MVP.
В варианте sqlite вы увидите много кода, который часто дублируется и использует базу данных в классах UsersDbHelper и LocalUserDataSource . Запросы строятся с помощью ContentValues , а данные, возвращаемые объектами Cursor , читаются столбец за столбцом. Весь этот код способствует появлению неявных ошибок. Например, можно пропустить добавление столбца в запрос или неправильно собрать объект из базы данных.
Давайте посмотрим, как Room улучшит наш код. Изначально мы просто копируем классы из варианта sqlite и постепенно будем изменять их.
Шаг 1. Обновление зависимостей gradle
Зависимости для Room доступны через новый Google Maven-репозиторий. Просто добавьте его в список репозиториев в вашем основном файле build.gradle :
Определите версию библиотеки Room в том же файле. Пока она находится в альфа-версии, но следите за обновлениями версий на страницах для разработчиков:
В вашем файле app/build.gradle добавьте зависимости для Room:
Чтобы мигрировать на Room, нам нужно увеличить версию базы данных, а для сохранения пользовательских данных нам потребуется реализовать класс Migration. Чтобы протестировать миграцию, нам нужно экспортировать схему. Для этого добавьте следующий код в файл app/build.gradle :
Шаг 2. Обновление классов модели до сущностей
Room создаёт таблицу для каждого класса, помеченного @Entity. Поля в классе соответствуют столбцам в таблице. Следовательно, классы сущностей, как правило, представляют собой небольшие классы моделей, которые не содержат никакой логики. Наш класс User представляет модель для данных в базе данных. Итак, давайте обновим его, чтобы сообщить Room, что он должен создать таблицу на основе этого класса:
- Аннотируйте класс с помощью @Entity и используйте свойство tableName , чтобы задать имя таблицы.
- Задайте первичный ключ, добавив аннотацию @PrimaryKey в правильные поля — в нашем случае это идентификатор пользователя.
- Задайте имя столбцов для полей класса, используя аннотацию @ColumnInfo(name = «column_name») . Этот шаг можно пропустить, если ваши поля уже названы так, как следует назвать столбец.
- Если в классе несколько конструкторов, добавьте аннотацию @Ignore , чтобы указать Room, какой следует использовать, а какой — нет.
Примечание: для плавной миграции обратите пристальное внимание на имена таблиц и столбцов в исходной реализации и убедитесь, что вы правильно устанавливаете их в аннотациях @Entity и @ColumnInfo .
Шаг 3. Создание объектов доступа к данным (DAO)
DAO отвечают за определение методов доступа к базе данных. В первоначальной реализации нашего проекта на SQLite все запросы к базе данных выполнялись в классе LocalUserDataSource , где мы работали с объектами Cursor . В Room нам не нужен весь код, связанный с курсором, и мы можем просто определять наши запросы, используя аннотации в классе UserDao .
Например, при запросе всех пользователей из базы данных Room выполняет всю «тяжелую работу», и нам нужно только написать:
Шаг 4. Создание базы данных
Мы уже определили нашу таблицу Users и соответствующие ей запросы, но мы ещё не создали базу данных, которая объединит все эти составляющие Room. Для этого нам нужно определить абстрактный класс, который расширяет RoomDatabase . Этот класс помечен @Database , в нём перечислены объекты, содержащиеся в базе данных, и DAO, которые обращаются к ним. Версия базы данных должна быть увеличена на 1 в сравнении с первоначальным значением, поэтому в нашем случае это будет 2.
Поскольку мы хотим сохранить пользовательские данные, нам нужно реализовать класс Migration , сообщающий Room, что он должен делать при переходе с версии 1 на 2. В нашем случае, поскольку схема базы данных не изменилась, мы просто предоставим пустую реализацию:
Создайте объект базы данных в классе UsersDatabase , определив имя базы данных и миграцию:
Чтобы узнать больше о том, как реализовать миграцию баз данных и как они работают под капотом, посмотрите этот пост.
Шаг 5. Обновление репозитория для использования Room
Мы создали нашу базу данных, нашу таблицу пользователей и запросы, так что теперь пришло время их использовать. На этом этапе мы обновим класс LocalUserDataSource для использования методов UserDao . Для этого мы сначала обновим конструктор: удалим Context и добавим UserDao . Конечно, любой класс, который создаёт экземпляр LocalUserDataSource , также должен быть обновлен.
Далее мы обновим методы LocalUserDataSource , которые делают запросы с помощью вызова методов UserDao . Например, метод, который запрашивает всех пользователей, теперь выглядит так:
А теперь время запустить то, что у нас получилось.
Одна из лучших функций Room — это то, что если вы выполняете операции с базой данных в главном потоке, то ваше приложение упадёт со следующим сообщением об ошибке:
Один надёжный способ переместить операции ввода-вывода из основного потока — это создать новый Runnable , который будет создавать новый поток для каждого запроса к базе данных. Поскольку мы уже используем этот подход в варианте sqlite, никаких изменений не потребовалось.
Шаг 6. Тестирование на устройстве
Мы создали новые классы — UserDao и UsersDatabase и изменили наш LocalUserDataSource для использования базы данных Room. Теперь нам нужно их протестировать.
Тестирование UserDao
Чтобы протестировать UserDao , нам нужно создать тестовый класс AndroidJUnit4 . Потрясающая особенность Room — это возможность создавать базу данных в памяти. Это исключает необходимость очистки после каждого теста.
Нам также нужно убедиться, что мы закрываем соединение с базой данных после каждого теста.
Например, чтобы протестировать вход пользователя, мы добавим пользователя, а затем проверим, сможем ли мы получить этого пользователя из базы данных.
Тестирование использования UserDao в LocalUserDataSource
Убедиться, что LocalUserDataSource по-прежнему работает правильно, легко, поскольку у нас уже есть тесты, которые описывают поведение этого класса. Всё, что нам нужно сделать, это создать базу данных в памяти, получить из нее объект UserDao и использовать его в качестве параметра для конструктора LocalUserDataSource .
Опять же, нам нужно убедиться, что мы закрываем базу данных после каждого теста.
Тестирование миграции базы данных
Подробнее почитать о том, как реализовать тесты миграции баз данных, а также, как работает MigrationTestHelper , можно в этом посте.
Вы также можете посмотреть код из более детального примера приложения миграции.
Шаг 7. Удаление всего ненужного
Удалите все неиспользуемые классы и строки кода, которые теперь заменены функциональностью Room. В нашем проекте нам просто нужно удалить класс UsersDbHelper , который расширял класс SQLiteOpenHelper .
Если у вас есть большая и более сложная база данных, и вы хотите постепенно перейти на Room, то рекомендуем этот пост.
Теперь количество стандартного кода, подверженного ошибкам, уменьшилось, запросы проверяются во время компиляции, и всё тестируется. За 7 простых шагов мы смогли мигрировать наше существующее приложение на Room. Пример приложения можете посмотреть здесь.