上一篇文章地址:Android 使用Room操作SQLite数据库让其变得无比高效和简洁(教程一)
下一篇文章地址:
Android使用Room操作SQLite数据库让其变得无比高效和简洁(进一步完善用RecyclerView显示数据库中的数据)
Android 使用Room操作数据库进行数据库版本的升级和迁移
这篇文章我们将上一个demo进行了四个方面的完善,
- 引入了LiveData
- 引入了AsyncTask后台执行
- 将WordDataBase这个类,修改为了单例模式
- 引入了ViewModel,使用ViewModel来管理界面的数据,使得MainActivity中的代码得到了精简,只管理界面的操作,跟操作数据没有直接的关联。
布局页面还是一样的不再给出代码
首先修改了WordDao这里面的代码,引入了LiveData
//访问数据库操作的接口 @Dao public interface WordDao { //添加数据 @Insert void insertWords(Word...words); @Delete void deleteWords(Word...words); @Query("DELETE FROM WORD") void deleteAllWords(); @Update void updateWords(Word...words); @Query("SELECT * FROM WORD ORDER BY ID DESC") // List<Word> getAllWords(); LiveData<List<Word>> getAllWordsLive(); }
之后将WordDataBase改为了单例模式,代码如下:
// 参数1:实体类 参数2:数据库版本号 参数3:禁止将数据库架构导入到给定的文件夹中 @Database(entities = {Word.class},version = 1,exportSchema = false) public abstract class WordDataBase extends RoomDatabase { private static WordDataBase INSTANCE; public 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(); }
之后创建WordViewModel类,在创建WordViewModel类之前,应该创建一个仓库类WordRepository,来作为中介,通过这个仓库类来获取和存储数据
WordRepository类如下:
public class WordRepository { private LiveData<List<Word>> allWordsLive; private WordDao wordDao; public WordRepository(Context context) { WordDataBase wordDataBase = WordDataBase.getDatabase(context); wordDao = wordDataBase.getWordDao(); allWordsLive = wordDao.getAllWordsLive(); } public void insertWords(Word... words) { new InsertAsyncTask(wordDao).execute(words); } public void updateWords(Word... words) { new UpdateAsyncTask(wordDao).execute(words); } public void deleteAllWords() { new DeleteAllAsyncTask(wordDao).execute(); } public void deleteWords(Word... words) { new DeleteAsyncTask(wordDao).execute(words); } public LiveData<List<Word>> getAllWordsLive() { return allWordsLive; } private static class InsertAsyncTask extends AsyncTask<Word, Void, Void> { private WordDao wordDao; public InsertAsyncTask(WordDao wordDao) { this.wordDao = wordDao; } @Override protected Void doInBackground(Word... words) { wordDao.insertWords(words); return null; } } private static class UpdateAsyncTask extends AsyncTask<Word, Void, Void> { private WordDao wordDao; public UpdateAsyncTask(WordDao wordDao) { this.wordDao = wordDao; } @Override protected Void doInBackground(Word... words) { wordDao.updateWords(words); return null; } } private static class DeleteAsyncTask extends AsyncTask<Word, Void, Void> { private WordDao wordDao; public DeleteAsyncTask(WordDao wordDao) { this.wordDao = wordDao; } @Override protected Void doInBackground(Word... words) { wordDao.deleteWords(words); ; return null; } } private static class DeleteAllAsyncTask extends AsyncTask<Void, Void, Void> { private WordDao wordDao; public DeleteAllAsyncTask(WordDao wordDao) { this.wordDao = wordDao; } @Override protected Void doInBackground(Void... voids) { wordDao.deleteAllWords(); return null; } } }
之后创建WordViewModel类管理数据:
public class WordViewModel extends AndroidViewModel { private WordDao wordDao; private WordRepository wordRepository; public WordViewModel(@NonNull Application application) { super(application); wordRepository = new WordRepository(application); } public LiveData<List<Word>> getAllWordsLive() { return wordRepository.getAllWordsLive(); } public void insertWords(Word... words) { wordRepository.insertWords(words); } public void updateWords(Word... words) { wordRepository.updateWords(words); } public void deleteAllWords() { wordRepository.deleteAllWords(); } public void deleteWords(Word... words) { wordRepository.deleteWords(words); } }
最后自然是MainActivity中的代码,这次里面的代码就非常的精简了:
public class MainActivity extends AppCompatActivity { private Button btn_insert, btn_clear, btn_update, btn_delete; private TextView tv_text; private WordViewModel wordViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // wordDataBase = Room.databaseBuilder(this, WordDataBase.class, "word_database") // .build(); btn_insert = findViewById(R.id.btn_insert); btn_clear = findViewById(R.id.btn_clear); btn_update = findViewById(R.id.btn_update); btn_delete = findViewById(R.id.btn_delete); tv_text = findViewById(R.id.tv_text); // wordViewModel =new WordViewModel(getApplication()); wordViewModel = ViewModelProviders.of(this).get(WordViewModel.class); wordViewModel.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"); } tv_text.setText(text.toString()); } }); btn_insert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Word word1 = new Word("Hello", "你好!"); Word word2 = new Word("World", "世界!"); // wordDao.insertWords(word1, word2); wordViewModel.insertWords(word1, word2); } }); btn_clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // wordDao.deleteAllWords(); wordViewModel.deleteAllWords(); } }); btn_update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Word word = new Word("Hi", "你好啊"); word.setId(120); // wordDao.updateWords(word); wordViewModel.updateWords(word); } }); btn_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Word word = new Word("Hi", "你好啊"); word.setId(120); // wordDao.deleteWords(word); wordViewModel.deleteWords(word); } }); } }
后续会持续更新Room操作数据库的相关内容~ 有不当之处 也可以在评论区留言指出!