Android Room Use Cases

This method introduces the content using Android Room stored data to the local database.

 The following is the official Android Room description document:

Persistence Library Room
(briefly Room Library) https://developer.android.com/topic/libraries/architecture/room
the Save A local Database in a using the Data Room
(Room user guide) https://developer.android.com / Training / Data-Storage / Room /
the Android Room View with a - the Java
(example of Room) https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0

I. Introduction
  Room is an object-relational mapping (ORM) library. You can easily convert SQLite table data as Java objects. Room Check SQLite statement at compile time.

  Room SQLite provides an abstraction layer, so that, database access may be performed smoothly while making the most of SQLite.

1.1 Add dependence

 Add rely on build.gradle

dependencies {

    def room_version = "2.2.0-beta01"

    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

}

Then add the following in build.gradle, but otherwise build:

android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [
                    "room.schemaLocation":"$projectDir/schemas".toString(),
                    "room.incremental":"true",
                    "room.expandProjection":"true"]
            }
        }
    }
}

1.2 assembly Room
  Room has three main components:

Database: contains the database holder, and the main access point as the underlying data associated with App persistent connection.

With @Database annotated classes should meet the following criteria:

Is an inherited to RoomDatabase abstract class.
It contains the list of entities associated with the database in the annotation.
Abstract methods comprise having a zero arguments, and returns the class annotated with @Dao.
At runtime, you can call Room.databaseBuilder () or Room.inMemoryDatabaseBuilder () Gets Database instance.

Entity: a table (Table) within the database.

DAO: contains methods for accessing the database.

1.3 Room relationships among the components
  generally use Room follows:

App obtain database access objects associated with the database (DAO) by Room of the Database.
Then, App use DAO Entity acquired from the database, and save the changes to the database Entity.
Finally, APP uses the data tables in Entity getting and setting the database.
  The relationship between the various components shown in Figure -1 Room:

Two, Entity (entity)
  When using a Room persistent database (Room persistence library), the relevant set of fields need to be defined as Entity. For each Entity, it will create a table (Table) in the Database object associated with it in.

The Entity class must refer to an array of Database class by entities.

  The following code fragment shows how to define Entity:

package com.example.jetpackdemo;

import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity
public class Word {

    @PrimaryKey(autoGenerate = true)
    private  Integer id;

    private String word;

    private String chinese;

    public Word(String word, String chinese) {
        this.word = word;
        this.chinese = chinese;
    }

    public Integer getId() {
        return id;
    }

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

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public String getChinese() {
        return chinese;
    }

    public void setChinese(String chinese) {
        this.chinese = chinese;
    }

    @Override
    public String toString() {
        return "Word{" +
                "id=" + id +
                ", word='" + word + '\'' +
                ", chinese='" + chinese + '\'' +
                '}';
    }
}

law. In providing getter and setter methods, the need to comply Room JavaBeans agreement.

2.1 Set Table Name
  Room Table default class name as the name of the database. Table names can be set by the tableName property @Entity.

(Note: in SQLite, Table names are not case sensitive.)

@Entity(tableName = "word")
public class Word { }

Three, DAO (Data access object)
  in Room persistent library using data access objects (data access objects, DAOs) App access data. Dao collection of objects is the main component Room, as each DAO database access method that provides an abstraction of App.

  Access to the database by using DAO, rather than through direct query builder or query, you can separate the different components of the database schema. In addition, when testing applications, DAOs can easily simulate database access.

  DAO may be an interface (interface), or may be an abstract class (abstract class). If it is an abstract class, you may have a constructor, which receives only a RoomDatabase parameter. At compile time, Room create a specific implementation for each DAO.

package com.example.jetpackdemo;

import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;

import java.util.List;

@Dao
public interface WordDao {

    @Insert
    void insert(Word...words);

    @Update
    void update(Word... words);

    @Query("delete from word")
    void deleteAll();

    @Query("select * from word")
    List<Word> findAll();

}

Note: unless you call allowMainThreadQueries () in the constructor, otherwise Room does not support database access on the main thread, because it might be time to lock UI. However, asynchronous query (return LiveData or Flowable example queries) are not bound by this rule, because they will be asynchronous query on a background thread when needed.

3.4.2 query with parameters

  In most cases, it is necessary to pass parameters to the query to perform a filtering operation, for example, need only display a certain age is greater than the User. At this time, we can use the method parameters.

@Dao
public interface MyDao {
    @Query("SELECT * FROM user WHERE age > :minAge")
    public User[] loadAllUsersOlderThan(int minAge);
}

At compile time, Room using the  minAge method parameter matching  :minAge binding parameters. If a mismatch exists, a compile error will occur.

  You can also pass multiple parameters in the query or multiple references to them.

@Dao
public interface MyDao {
    @Query("SELECT * FROM user WHERE age BETWEEN :minAge AND :maxAge")
    public User[] loadAllUsersBetweenAges(int minAge, int maxAge);

    @Query("SELECT * FROM user WHERE first_name LIKE :search " +
           "OR last_name LIKE :search")
    public List<User> findUserWithName(String search);
}

Four, Database

  In Room persistent database by  @Database category to access the database.

4.1 Definitions Database

  The following code fragment shows how to define Database:

package com.example.jetpackdemo;

import androidx.room.Database;
import androidx.room.RoomDatabase;

@Database(entities = {Word.class},version = 1, exportSchema = false)
public abstract class WordDatabase extends RoomDatabase {
    public abstract WordDao getWordDao();
}

Fifth, test cases

Create a RoomActivity

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RoomActivity">

    <ScrollView
        android:id="@+id/scrollView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.6" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:text="@string/btn5"
        app:layout_constraintBottom_toTopOf="@+id/guideline3"
        app:layout_constraintEnd_toStartOf="@+id/guideline4"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline3" />

    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="@string/btn6"
        app:layout_constraintBottom_toTopOf="@+id/guideline3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline4"
        app:layout_constraintTop_toTopOf="@+id/guideline3" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.75" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.875513" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn8"
        app:layout_constraintBottom_toTopOf="@+id/guideline5"
        app:layout_constraintEnd_toStartOf="@+id/guideline4"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline5" />

    <Button
        android:id="@+id/button8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="@string/btn9"
        app:layout_constraintBottom_toTopOf="@+id/guideline5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline4"
        app:layout_constraintTop_toTopOf="@+id/guideline5" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="@+id/scrollView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.jetpackdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Insert;
import androidx.room.Room;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;

public class RoomActivity extends AppCompatActivity {

    private WordDatabase wordDatabase;
    private WordDao wordDao;
    private Button btn5,btn6,btn7,btn8;
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room);

        wordDatabase = Room.databaseBuilder(this,WordDatabase.class,"word_database").allowMainThreadQueries().build();
        wordDao = wordDatabase.getWordDao();
        btn5 = findViewById(R.id.button5);
        btn6 = findViewById(R.id.button6);
        btn7 = findViewById(R.id.button7);
        btn8 = findViewById(R.id.button8);

        tv = findViewById(R.id.textView);

        btn5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Word word1 = new Word("hello","你好");
                Word word2 = new Word("world","世界");

                wordDao.insert(word1,word2);
                show();
            }
        });

        btn6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                show();
            }
        });

        btn7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Word word = new Word("hi","你好");
                word.setId(5);
                wordDao.update(word);
                show();
            }
        });

        btn8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                wordDao.deleteAll();
                show();
            }
        });

    }

    private void show()
    {
        List<Word> list = wordDao.findAll();
        StringBuilder sb =new StringBuilder();
        for (Word w : list){
            sb.append(w.toString()+"\n");
        }
        tv.setText(sb.toString());
    }

}

 Sixth, the effect of:

 

Guess you like

Origin www.cnblogs.com/zoro-zero/p/11413343.html