深入浅出AndroidJava 核心技术Android核心技术

Room使用

2021-07-22  本文已影响0人  安卓技术砖家

Android 应用数据存储简单来说有这么几种:

当需要本地存储大量数据的时候,文件存储频繁读取文件内容修改保存是很耗时,SharedPreference 无法支持大量数据。这时候本地原生的SQLite虽然符合,但是编程过程不太友好,所幸的是Google在其基础上的封装,就有了今天推荐的轻量级数据库——Room


导入依赖

implementation "android.arch.persistence.room:runtime:2.0.0"
annotationProcessor "android.arch.persistence.room:compiler:2.0.0"

创建数据库

在数据库中创建一张表,表中设计我们要操作的数据对象。在Room中对应的注解如下:

创建一个学生数据库StudentDB, 这个数据库有一张学生表StudentEntity, StudentDao用于提供对学生表的各种增删查改。StudentDB代码如下:

@Database(entities = {StudentEntity.class}, version = 1 )
public abstract class StudentDB extends RoomDatabase {
    public abstract StudentDao studentDao();
}

StudentEntity代码如下:

@Entity
public class StudentEntity {
    @PrimaryKey
    private long studentID;
    private String name;
    private int age;

    public StudentEntity() {
    }

    @Ignore
    public StudentEntity(long studentID, String name, int age) {
        this.studentID = studentID;
        this.name = name;
        this.age = age;
    }

    public long getStudentID() {
        return studentID;
    }

    public void setStudentID(long studentID) {
        this.studentID = studentID;
    }

    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;
    }

    @Override
    public String toString() {
        return "StudentEntity{" +
                "studentID=" + studentID +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

@PrimaryKey是我们设置的主键,因为主键类型Long, INT,我们也可以写成@PrimaryKey(autoGenerate = true),选择由数据库自动生成。StudentDao代码如下:

@Dao
public interface StudentDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(StudentEntity studentEntity);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertList(List<StudentEntity> studentEntities);

    @Query("delete from StudentEntity where studentID=:studentID")
    void deleteStudent(long studentID);

    @Query("select * from StudentEntity")
    List<StudentEntity> getAll();

    @Query("select * from StudentEntity where studentID=:studentID")
    StudentEntity queryStudent(long studentID);

    @Update
    void updateStudent(StudentEntity studentEntity);   
}

操作对象StudentDao 的增删查改(数据可以批量也可单独操作,如插入这边写了批量和单独的操作,其它也是类似,故不多写)

插入数据,只需要标记上Insert注解,onConflict = OnConflictStrategy.REPLACE表明插入一条数据如果主键已经存在,则可以直接替换旧的数据。

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(StudentEntity studentEntity);

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertList(List<StudentEntity> studentEntities);

删除操作,可以执行我们写入的SQL语句

@Query("delete from StudentEntity where studentID=:studentID")
void deleteStudent(long studentID);

也可通过@Delete传入对象删除

@Delete
void deleteStudent(StudentEntity studentEntity);

查询,通过注解@Query 执行SQL语句

@Query("select * from StudentEntity")
List<StudentEntity> getAll();

@Query("select * from StudentEntity where studentID=:studentID")
StudentEntity queryStudent(long studentID);

更改,通过注解@Update传入对象更新数据

@Update
void updateStudent(StudentEntity studentEntity);

在主界面创建本地持久化的数据库。第一个传入的是上下文,第二个是我们注解了的@Database与扩展了RoomDatabase的类,第三个是创建的数据库文件的名称,是个字符串。

方法一:对数据增删查改需要在后台操作

StudentDB studentDB = Room.databaseBuilder(this, StudentDB.class, dataBaseName).build();

如果直接在UI线程操作,会报异常如下:

Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

这里结合RxJava写出个方法一的简单调用。首先引入RxJava 2.0版本的依赖

implementation 'io.reactivex.rxjava2:rxjava:2.1.1'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'

插入一条数据的代码

final StudentEntity studentEntity = new StudentEntity(1, "name", 18);
Observable.create(new ObservableOnSubscribe<StudentEntity>() {
    @Override
    public void subscribe(ObservableEmitter<StudentEntity> e) throws Exception {
        studentDB.studentDao().insert(studentEntity);
        //将插入成功的学生id数据传到主线程
        e.onNext(studentDB.studentDao().queryStudent(studentEntity.getStudentID()));}})
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    .subscribe(new Consumer<StudentEntity>() {
        @Override
        public void accept(StudentEntity studentEntity) throws Exception {
            //显示插入成功的数据
            tv_content.setText("插入数据:"+studentEntity.toString());
        }
    });

方法二:通过设置allowMainThreadQueries()允许在主线程操作

StudentDB studentDB = Room.databaseBuilder(this, StudentDB.class, dataBaseName)
                      .allowMainThreadQueries()
                      .build();

可以直接调用增删查改

studentDB.studentDao().insert(StudentEntity);
studentDB.studentDao().deleteStudent(long studentID);

注意:由于数据库的操作是耗时的,画面在60fps则不会感觉到卡顿,假设大量数据的查询加绘制界面的时间超过16ms ,方法二会导致应用看起是卡顿,甚至ANR。对于是否允许UI线程运行数据库操作,取决小伙伴们自身开发的APP的需求


使用数据库

最后给出使用Room数据库MainActivity的代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private StudentDB studentDB;
    private String dataBaseName = "StudentDB";
    private TextView tv_content;
    private Button btn_insert, btn_delete, btn_query, btn_update, btn_showAll;
    private EditText edt_insert_num, edt_insert_name, edt_insert_age, edt_delete_num, edt_query_num,
            edt_update_num, edt_update_name, edt_update_age;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initDataBase();
        initView();
    }

    private void initDataBase() {
        /**
         * 后台操作
         * */
        //studentDB = Room.databaseBuilder(this, StudentDB.class, dataBaseName).build();
        /**
         * 主线程操作
         * */
        studentDB = Room.databaseBuilder(this, StudentDB.class, dataBaseName)
                .allowMainThreadQueries()
                .build();
    }

    private void initView() {
        ...
    }

    @Override
    public void onClick(View v) {
        ...
        switch (v.getId()) {
            case R.id.btn_insert:
                insertData();
                break;
            case R.id.btn_delete:
                deleteData();
                break;
            case R.id.btn_query:
                queryData();
                break;
            case R.id.btn_update:
                updateData();
                break;
            case R.id.btn_showAll:
                showAll();
                break;
            default:
        }
    }

    private void showAll() {
        // 在后台运行
        /*Observable.create(new ObservableOnSubscribe<List<StudentEntity>>() {
            @Override
            public void subscribe(ObservableEmitter<List<StudentEntity>> emitter) throws Exception {
                emitter.onNext(studentDB.studentDao().getAll());
            }
        })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Consumer<List<StudentEntity>>() {
                @Override
                public void accept(List<StudentEntity> data) throws Exception {
                    tv_content.setText(data.toString());
                }
            });
        */
        // 运行到主线程:
        tv_content.setText("展示所有数据:"+ studentDB.studentDao().getAll().toString());
    }

    private void updateData() {
        ...
        long studentID = Long.parseLong(edt_update_num.getText().toString());
        String name = edt_update_name.getText().toString();
        int age = Integer.parseInt(edt_update_age.getText().toString());
        StudentEntity studentEntity = new StudentEntity(studentID, name, age);
        tv_content.setText("更新数据:"+studentEntity.toString());
        studentDB.studentDao().updateStudent(studentEntity);
    }

    private void queryData() {
        ...
        long studentID = Long.parseLong(edt_query_num.getText().toString());
        StudentEntity studentEntity = studentDB.studentDao().queryStudent(studentID);
        tv_content.setText("查询数据:"+studentEntity.toString());
    }

    private void deleteData() 
        ...
        long studentID = Long.parseLong(edt_delete_num.getText().toString());
        tv_content.setText("删除数据:"+studentDB.studentDao().queryStudent(studentID));
        studentDB.studentDao().deleteStudent(studentID);
    }

    private void insertData() {
        ...
        long studentID = Long.parseLong(edt_insert_num.getText().toString());
        String name = edt_insert_name.getText().toString();
        int age = Integer.parseInt(edt_insert_age.getText().toString());
        //数据库插入操作:当学号一样则替换
        final StudentEntity studentEntity = new StudentEntity(studentID, name, age);
        //final StudentEntity studentEntity = new StudentEntity(1, "name", 18);
        /*Observable.create(new ObservableOnSubscribe<StudentEntity>() {
            @Override
            public void subscribe(ObservableEmitter<StudentEntity> e) throws Exception {
                studentDB.studentDao().insert(studentEntity);
                //studentDB.studentDao().queryStudent(studentEntity.getStudentID());
                e.onNext(studentDB.studentDao().queryStudent(studentEntity.getStudentID()));
            }})
        .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Consumer<StudentEntity>() {
                @Override
                public void accept(StudentEntity studentEntity) throws Exception {
                    tv_content.setText("插入数据:" + studentEntity.toString());
                }
            });
        */
        tv_content.setText("插入数据:" + studentEntity.toString());
        studentDB.studentDao().insert(studentEntity);
    }
}
上一篇下一篇

猜你喜欢

热点阅读