The use of Android Room database is introduced in detail

  • 2021-08-21 21:32:31
  • OfStack

Preface

Google has finally released a library related to SQLite. The previous 1 straight is tossing back and forth between SQLite, XUtils, greenDao and Realm databases. Now there is finally a more "orthodox" database.

What is Room?

Room is a persistent database.

The Room persistence library provides the abstraction layer of SQLite to allow smooth database access while taking full advantage of SQLite.

Why did you choose Room?

As I mentioned earlier, there are many open source databases for everyone to use, so why should we learn to use this library? Of course, it is not the reason of "being unorthodox" as I said earlier.

Because Room has the following advantages:

① The SQL query validates at compile time-checking every @ Query and @ Entity and so on at compile time, which means there is no risk of any run-time errors that could cause the application to crash (and it checks not only for syntax problems, but also for the existence of the table.)

Less template code

③ Integration with LiveData

How to use it?

1. Add the following dependencies to app/build. gradle


implementation 'android.arch.persistence.room:runtime:1.0.0'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'

You can click here to view the latest dependent version number

2. Create JavaBean


@Entity
public class User {
 
 @PrimaryKey(autoGenerate = true)// Whether the primary key grows automatically, the default is false
 private int id;
 private String name;
 private int age;

 public int getId() {
 return id;
 }

 public void setId(int id) {
 this.id = id;
 }

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public int getAge() {
 return age;
 }

 public void setAge(int age) {
 this.age = age;
 }
 // Here's getter/setter Method is a must 
 // Here's getter/setter Method is a must 
 // Here's getter/setter Method is a must 
 // Say something important 3 Pass 
}

Here you need to annotate the class with @ Entity

Must have at least 1 primary key @ PrimaryKey

3. Create Dao

Next, we need to create DAO for our entity. DAO stands for data access objects, so it is one way to tell our database how to manipulate data:


@Dao
public interface UserDao {
 @Query("SELECT * FROM user")
 List<User> getAllUsers();

 @Insert
 void insert(User... users);

 @Update
 void update(User... users);

 @Delete
 void delete(User... users);
}

Annotate the interface with @ Dao

@ Insert, @ Update, @ Delete, @ Query represent our common operations of inserting, updating, deleting and querying databases

@ Insert, @ Update, @ Delete can pass in many different parameters. For example:


@Insert
void insert(User... users);

@Insert
void insert(User user);

@Insert
void insert(List<User> userLists);

Similarly, @ Query can return many different types.


@Query("SELECT * FROM user")
List<User> getAllUsers();

@Query("SELECT * FROM user WHERE id=:id")
User getUser(int id);

@Query("SELECT * FROM user")
Cursor getUserCursor();

Of course, in addition to these, we can also pass in 1 restrictor. For example,


@Query("SELECT * FROM user WHERE age=:age")
List<User> getUsersByAge(int age);

@Query("SELECT * FROM user WHERE age=:age LIMIT :max")
List<User> getUsersByAge(int max, int... age);

4. Create a database


@Database(entities = { User.class }, version = 1,exportSchema = false)
public abstract class UserDatabase extends RoomDatabase {

 private static final String DB_NAME = "UserDatabase.db";
 private static volatile UserDatabase instance;

 static synchronized UserDatabase getInstance(Context context) {
 if (instance == null) {
  instance = create(context);
 }
 return instance;
 }

 private static UserDatabase create(final Context context) {
 return Room.databaseBuilder(
  context,
  UserDatabase.class,
  DB_NAME).build();
 }

 public abstract UserDao getUserDao();
}

Here you annotate the class with @ Database and add the table name, the database version (which increases whenever we change the contents of the database), so here you use exportSchema = false

Note: Add exportSchema = false in addition to the class and database version of the table map or you will be warned.

Error: (10, 17) Warning: Schema export directory is not provided the annotation processor ES1117EN ES1118EN cannot provided the room provide room. schemaLocation annotation processor argument set exportSchema to false false.

We abstract the getUserDao () method, which is necessary.

5. Working with a database

We can finally operate our database. But all operations must be done in the background thread. You can do this by using AsyncTask, Thread, Handler, RxJava or other means.

If it is not executed in the background thread, and it is not indicated that it can be operated in the main thread, the following error will be reported.

Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

For example, we can insert data like this


User user=new User();
user.setName("name1");
user.setAge(18);
UserDatabase
 .getInstance(context)
 .getUserDao()
 .insert(user);

Or so


List<User> allUsers = UserDatabase
 .getInstance(RoomActivity.this)
 .getUserDao()
 .getAllUsers();

Ok, that's all the basic ways to use it.


Related articles: