Android JetPack学习总结(五)

Room(一)

添加依赖
dependencies {
      def room_version = "2.2.3"
      implementation "androidx.room:room-runtime:$room_version"
      annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor
      // Test helpers
      testImplementation "androidx.room:room-testing:$room_version"
    }

需要先添加远程仓库

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter()
    }
}
创建entity、Dao、Database

在创建这些类时使用注解以声明。

Entity:

@Entity
public class Word {
    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "english_word")
    private String word;
    @ColumnInfo(name = "chinese_meaning")
    private String chineseMeaning;

    public Word(int id, String word, String chineseMeaning) {
        this.id = id;
        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;
    }
}

Dao:

@Dao //database access object
public interface WordDao {
    @Insert
    void insertWords(Word ... words);

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

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

    @Query("DELETE FROM WORD")
    void deleteAllWords();

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

Database

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

我们并没有去重写dao接口中的方法,也没有重写database类中的get方法,这些过程都是Room的注解帮助我们完成的,这看上去莫名其妙,其实确实很莫名其妙。

以dao中的方法为例,Room帮我们自动写全了这些方法:

//WordDao_Imp
@Override
  public void insertWords(final Word... words) {
    __db.assertNotSuspendingTransaction();
    __db.beginTransaction();
    try {
      __insertionAdapterOfWord.insert(words);
      __db.setTransactionSuccessful();
    } finally {
      __db.endTransaction();
    }
  }

  @Override
  public void deleteWords(final Word... words) {
    __db.assertNotSuspendingTransaction();
    __db.beginTransaction();
    try {
      __deletionAdapterOfWord.handleMultiple(words);
      __db.setTransactionSuccessful();
    } finally {
      __db.endTransaction();
    }
  }

  @Override
  public int updateWords(final Word... words) {
    __db.assertNotSuspendingTransaction();
    int _total = 0;
    __db.beginTransaction();
    try {
      _total +=__updateAdapterOfWord.handleMultiple(words);
      __db.setTransactionSuccessful();
      return _total;
    } finally {
      __db.endTransaction();
    }
  }

  @Override
  public void deleteAllWords() {
    __db.assertNotSuspendingTransaction();
    final SupportSQLiteStatement _stmt = __preparedStmtOfDeleteAllWords.acquire();
    __db.beginTransaction();
    try {
      _stmt.executeUpdateDelete();
      __db.setTransactionSuccessful();
    } finally {
      __db.endTransaction();
      __preparedStmtOfDeleteAllWords.release(_stmt);
    }
  }

  @Override
  public List<Word> getAllWords() {
    final String _sql = "SELECT * FROM WORD ORDER BY ID desc";
    final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
    __db.assertNotSuspendingTransaction();
    final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
    try {
      final int _cursorIndexOfId = CursorUtil.getColumnIndexOrThrow(_cursor, "id");
      final int _cursorIndexOfWord = CursorUtil.getColumnIndexOrThrow(_cursor, "english_word");
      final int _cursorIndexOfChineseMeaning = CursorUtil.getColumnIndexOrThrow(_cursor, "chinese_meaning");
      final List<Word> _result = new ArrayList<Word>(_cursor.getCount());
      while(_cursor.moveToNext()) {
        final Word _item;
        final String _tmpWord;
        _tmpWord = _cursor.getString(_cursorIndexOfWord);
        final String _tmpChineseMeaning;
        _tmpChineseMeaning = _cursor.getString(_cursorIndexOfChineseMeaning);
        _item = new Word(_tmpWord,_tmpChineseMeaning);
        final int _tmpId;
        _tmpId = _cursor.getInt(_cursorIndexOfId);
        _item.setId(_tmpId);
        _result.add(_item);
      }
      return _result;
    } finally {
      _cursor.close();
      _statement.release();
    }
  }
获取、使用database和dao

获取:

//onCreated
wordDatabase= Room.databaseBuilder(this,WordDatabase.class,"WordDatabase")
                .allowMainThreadQueries()//强制允许在主线程进行数据库查询
                .build();

        wordDao=wordDatabase.getWordDao();

直接使用获取的dao,调用其方法就可以进行数据库查询:

//onCreated
bInsert=findViewById(R.id.insert);
        bInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Word word1=new Word("Hello","你好");
                Word word2=new Word("World","世界");
                wordDao.insertWords(word1,word2);
                updateView();
            }
        });

发表评论