最近接触了room,可以完成数据库的工作,使用的感觉有点像spring boot,一起来看看吧

效果和结构

效果如下,很简单,只是为了显示room的作用

作为一个demo,文件结构很简单

导入包

首先进入room导入依赖包,也就是下面的代码贴到build.gradle中的dependencies中,这里我删除kotlin相关

  def room_version = "2.2.1"

    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"
    // For Kotlin use kapt instead of annotationProcessor

    // optional - RxJava support for Room
    implementation "androidx.room:room-rxjava2:$room_version"

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "androidx.room:room-guava:$room_version"

    // Test helpers
    testImplementation "androidx.room:room-testing:$room_version"

实体类

然后构建word实体类,实体类我们可以用gsonFormat插件快速完成,具体可以自己搜索

这里构建单词实体时,通过PrimaryKey等注解的形式确定主键,属性列等

package com.example.roombaisic;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity
public class Word {

    /** * id : 0 * word : * chineseMeaning : */
    @PrimaryKey(autoGenerate = true)
    private int id;
    @ColumnInfo(name = "english_word")
    private String word;
    @ColumnInfo(name="chinese_meaning")
    private String chineseMeaning;

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

    public int getId() {
        return id;
    }

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

    public String getWord() {
        return word;
    }

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

    public String getChineseMeaning() {
        return chineseMeaning;
    }

    public void setChineseMeaning(String chineseMeaning) {
        this.chineseMeaning = chineseMeaning;
    }
}

然后创建WordDao,对word的增删改查操作都来自于此,这是个接口,由于注解可以帮我们执行sql语句,所以不需要实例化,非常方便

Word…words表示可以传任意参数

Dao层

package com.example.roombaisic;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.*;

import java.util.List;
//对数据库的操作

@Dao
public interface WordDao {
    @Insert
    void insertWords(Word... words);

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

    @Delete
    void deleteWords(Word... words);

    @Delete
    void deleteAllWords(List<Word>words);

    @Query("SELECT * FROM WORD ORDER BY ID DESC")
    List<Word> getAllWord();
}

数据库

最后时wordDatabase,很简单,注意时抽象类,因为同样不需要实例化,有多少个实体就有多少给Dao,都可以统一在wordDatabase中声明

package com.example.roombaisic;

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

android实现

完成了以上工作,就到了android时间了,就剩下一个activity的java和xml文件

activity_main.xml

<?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=".MainActivity">



    <ScrollView
        android:layout_width="411dp"
        android:layout_height="367dp"
        android:layout_marginBottom="404dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0">
        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </ScrollView>

    <Button
        android:id="@+id/btn_insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="248dp"
        android:text="insert"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.256"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/btn_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="248dp"
        android:text="delete"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.48"
        app:layout_constraintStart_toEndOf="@+id/btn_insert" />

    <Button
        android:id="@+id/btn_update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="148dp"
        android:text="update"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.49"
        app:layout_constraintStart_toEndOf="@+id/btn_clear"
        app:layout_constraintTop_toBottomOf="@+id/btn_delete"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/btn_clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="80dp"
        android:layout_marginTop="32dp"
        android:text="clear"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_insert"
        app:layout_constraintVertical_bias="0.119" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity

package com.example.roombaisic;

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

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

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    TextView textView;
    Button btnInsert;
    Button btnDelete;
    Button btnUpdate;
    Button btnClear;

    WordDao wordDao;
    WordDatabase wordDatabase;
    ArrayList<Word>list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
		//通过room构建数据库
        wordDatabase = Room.databaseBuilder(this, WordDatabase.class, "wordDatabase")
                .allowMainThreadQueries()
                .build();
        //拿到wordDao
        wordDao = wordDatabase.getWordDao();
        init();
        initView();

    }

    private void initView() {
        btnInsert.setOnClickListener(this);
        btnDelete.setOnClickListener(this);
        btnUpdate.setOnClickListener(this);
        btnClear.setOnClickListener(this);
    }

    private void init() {
        btnInsert = (Button) findViewById(R.id.btn_insert);
        btnDelete = (Button) findViewById(R.id.btn_delete);
        btnUpdate = (Button) findViewById(R.id.btn_update);
        btnClear = (Button) findViewById(R.id.btn_clear);
        textView=(TextView)findViewById(R.id.text);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_insert:
                insertView();
                break;
            case R.id.btn_delete:
                deleteView();
                break;
            case R.id.btn_update:
                updateView();
                break;
            case R.id.btn_clear:
                clearView();
                break;
        }
    }

    private void clearView() {
        if (list !=null){
            wordDao.deleteAllWords(list);
        }
        updateView();

    }

    private void deleteView() {
    }

    private void insertView() {
        Word word1 = new Word( "hello", "你好");
        Word word2 = new Word( "world", "世界");
        wordDao.insertWords(word1, word2);
        updateView();
        Log.d(TAG, "insertView: 更新完毕");

    }
    //无论做什么操作后,都要更新一次text列表
    private void updateView() {
        list=(ArrayList<Word>) wordDao.getAllWord();

        StringBuilder text=new StringBuilder();
        for (int i = 0; i <list.size() ; i++) {
            Word word=list.get(i);
            text.append(word.getId()).append(" ").append(word.getWord()).append(" ").append(word.getChineseMeaning()).append("\n");
        }
        textView.setText(text.toString());
        Log.d(TAG, "insertView: 写入text完毕");

    }


}