1. Word 类不做修改
@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(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;
}
}
2. 修改 WordDao
@Dao //Database access object
public interface WordDao {
@Insert
void insertWords(Word... words);
@Update
void updateWords(Word... words);
@Delete
void deleteWords(Word... words);
@Query("DELETE FROM WORD")
void deleteAllWords();
@Query("SELECT * FROM WORD ORDER BY ID DESC")
LiveData<List<Word>> getAllWordsLive();
//List<Word> getAllWords();
}
3. 修改 WordDatabase,只允许生成一个实例
//singleton 只允许生成一个实例
@Database(entities = {Word.class}, version = 1, exportSchema = false)
public abstract class WordDatabase extends RoomDatabase {
private static WordDatabase INSTANCE;
//synchronized: 解决多个线程下调用,创建多个实例问题
static synchronized WordDatabase getDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(), WordDatabase.class, "word_database")
.build();
}
return INSTANCE;
}
public abstract WordDao getWordDao();
}
4. 创建 Repository:仓库 获取数据的意思, 代码进行归类
class WordRepository {
private WordDao wordDao;
private LiveData<List<Word>> allWordsLive;
WordRepository(Context context) {
WordDatabase wordDatabase = WordDatabase.getDatabase(context);
wordDao = wordDatabase.getWordDao();
allWordsLive = wordDao.getAllWordsLive();
}
LiveData<List<Word>> getAllWordsLive() {
return allWordsLive;
}
void insertWords(Word... words) {
new InsertAsyncTask(wordDao).execute(words);
}
void updateWords(Word... words) {
new UpdateAsyncTask(wordDao).execute(words);
}
void deleteWords(Word... words) {
new DeleteAsyncTask(wordDao).execute(words);
}
void deleteAllWords() {
new DeleteAllAsyncTask(wordDao).execute();
}
static class InsertAsyncTask extends AsyncTask<Word, Void, Void> {
private WordDao wordDao;
InsertAsyncTask(WordDao wordDao) {
this.wordDao = wordDao;
}
@Override
protected Void doInBackground(Word... words) {
wordDao.insertWords(words);
return null;
}
}
static class UpdateAsyncTask extends AsyncTask<Word, Void, Void> {
private WordDao wordDao;
UpdateAsyncTask(WordDao wordDao) {
this.wordDao = wordDao;
}
@Override
protected Void doInBackground(Word... words) {
wordDao.updateWords(words);
return null;
}
}
static class DeleteAsyncTask extends AsyncTask<Word, Void, Void> {
private WordDao wordDao;
DeleteAsyncTask(WordDao wordDao) {
this.wordDao = wordDao;
}
@Override
protected Void doInBackground(Word... words) {
wordDao.deleteWords(words);
return null;
}
}
static class DeleteAllAsyncTask extends AsyncTask<Void, Void, Void> {
private WordDao wordDao;
DeleteAllAsyncTask(WordDao wordDao) {
this.wordDao = wordDao;
}
@Override
protected Void doInBackground(Void... voids) {
this.wordDao.deleteAllWords();
return null;
}
}
}
5. 创建 ViewModel
public class WordViewModel extends AndroidViewModel {
private WordRepository wordRepository;
public WordViewModel(@NonNull Application application) {
super(application);
wordRepository = new WordRepository(application);
}
public LiveData<List<Word>> getAllWordsLive() {
return wordRepository.getAllWordsLive();
}
void insertWords(Word... words) {
wordRepository.insertWords(words);
}
void updateWords(Word... words) {
wordRepository.updateWords(words);
}
void deleteWords(Word... words) {
wordRepository.deleteWords(words);
}
void deleteAllWords() {
wordRepository.deleteAllWords();
}
}
6. 调用测试
public class MainActivity extends AppCompatActivity {
TextView textView;
Button btInsert, btUpdate, btDelete, btClear;
WordViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
viewModel = new ViewModelProvider(this).get(WordViewModel.class);
viewModel.getAllWordsLive().observe(this, new Observer<List<Word>>() {
@Override
public void onChanged(List<Word> words) {
StringBuilder text = new StringBuilder();
for (int i = 0; i < words.size(); i++) {
Word word = words.get(i);
text.append(word.getId()).append(":").append(word.getWord()).append("=").append(word.getChineseMeaning()).append("\n");
}
textView.setText(text.toString());
}
});
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bt_insert:
Word word1 = new Word("Hello", "你好!");
Word word2 = new Word("World", "世界!");
viewModel.insertWords(word1, word2);
break;
case R.id.bt_clear:
viewModel.deleteAllWords();
break;
case R.id.bt_update:
Word word = new Word("Hi", "嗨");
word.setId(51);
viewModel.updateWords(word);
break;
case R.id.bt_delete:
Word word_d = new Word("一", "1");
word_d.setId(52);
viewModel.deleteWords(word_d);
break;
}
}
};
btInsert = findViewById(R.id.bt_insert);
btClear = findViewById(R.id.bt_clear);
btUpdate = findViewById(R.id.bt_update);
btDelete = findViewById(R.id.bt_delete);
btDelete.setOnClickListener(listener);
btInsert.setOnClickListener(listener);
btClear.setOnClickListener(listener);
btUpdate.setOnClickListener(listener);
}
}