阅读 134

MVVMSmart系列文章--Jetpack的Room数据库使用

Room持久库提供了一个SQLite抽象层,让你访问数据库更加稳健,提升数据库性能。 该库帮助您在运行应用程序的设备上创建应用程序的数据缓存。这个缓存是你的应用程序唯一的真实来源,允许用户查看应用程序中关键信息的一致副本,而不管用户是否有Internet连接。room由google开发,google背书,是jetpack的重点架构组件我们没有理由不学习,google出品必属精品.

博文代码:在MVVMSmart项目中,

  • MVVMsmart地址:github.com/wzqjava/MVV…
  • 分支名称:MVVMSmart-kotlin(切换分支,readme会自动切换成对应语言)
  • 分支名称:MVVMSmart-java(切换分支,readme会自动切换成对应语言)
  • 基于谷歌最新AAC架构,MVVM设计模式的一套快速开发库,整合ViewModel+Lifecycles+Navigation+DataBinding+LilveData+Okhttp+Retrofit+RxJava+Glide等主流模块,满足日常开发需求。使用该框架可以快速开发高质量、易维护的Android应用.

效果图

  1. 项目效果图 此页为jetpack的navigation管理,点击ROOM数据库示例进入专门roomfragment.

  1. 数据库的增删改查,使用了jetpack建议的Repository

使用步骤

  1. 引入依赖
  • implementation "androidx.room:room-runtime:2.2.3"
  • // For Kotlin use kapt instead of annotationProcessor
  • annotationProcessor "androidx.room:room-compiler:2.2.3"
  1. 项目结构

  2. 结构解释

    • RoomSampleFragment UI层
    • RoomSampleViewModel viewmode业务层
    • WordRepository 仓库层
    • WordDao 操作数据的dao层(增删改查)
    • WordDatabase database
    • Word room的javabean
  3. 代码简介,都是测试过的代码,完全可商用

  4. 代码截图

RoomSampleFragment.java

package com.wzq.sample.ui.room_sample;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.wzq.mvvmsmart.base.BaseFragment;
import com.wzq.sample.R;
import com.wzq.sample.databinding.FragmentRoom1Binding;

import java.util.List;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;


/**
 * Create Date:2020/01/01
 *  实现Room数据的基本操作
 *  王志强
 */

public class RoomSampleFragment extends BaseFragment<FragmentRoom1Binding, RoomSampleViewModel> {


    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_room1;
    }

    @Override
    public int initVariableId() {
        return com.wzq.sample.BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        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");
                }
                binding.textView.setText(text.toString());
            }
        });
        binding.buttonInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Word word1 = new Word("Hello", "你好!");
                Word word2 = new Word("World", "世界!");
                viewModel.insertWords(word1, word2);
            }
        });

        binding.buttonClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.deleteAllWords();
            }
        });

        binding.buttonUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Word word = new Word("update", "更新!");
                word.setId(1);
                viewModel.updateWords(word);
            }
        });

        binding.buttonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Word word = new Word("update", "更新!");
                word.setId(1);
                viewModel.deleteWords(word);
            }
        });
    }
}

复制代码

RoomSampleViewModel.java

package com.wzq.sample.ui.room_sample;

import android.app.Application;

import com.wzq.mvvmsmart.base.BaseViewModel;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;


/**
 * Create Date:2020/01/01
 *  实现Room数据的基本操作
 *  王志强
 */
public class RoomSampleViewModel extends BaseViewModel {

    private WordRepository wordRepository;

    public RoomSampleViewModel(@NonNull Application application) {
        super(application);
        wordRepository = new WordRepository(application);
    }

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

}

复制代码

WordRepository.java

package com.wzq.sample.ui.room_sample;

import android.content.Context;
import android.os.AsyncTask;

import java.util.List;

import androidx.lifecycle.LiveData;

class WordRepository {
    private LiveData<List<Word>> allWordsLive;
    private WordDao wordDao;

    WordRepository(Context context) {
        WordDatabase wordDatabase = WordDatabase.getDatabase(context.getApplicationContext());
        wordDao = wordDatabase.getWordDao();
        allWordsLive = wordDao.getAllWordsLive();
    }

    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(Word... words) {
        new DeleteAllAsyncTask(wordDao).execute();
    }


    LiveData<List<Word>> getAllWordsLive() {
        return allWordsLive;
    }

    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) {
            wordDao.deleteAllWords();
            return null;
        }

    }
}

复制代码

WordDatabase.java

package com.wzq.sample.ui.room_sample;

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

//singleton
@Database(entities = {Word.class}, version = 1, exportSchema = false)
public abstract class WordDatabase extends RoomDatabase {
    private static WordDatabase INSTANCE;

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

复制代码

WordDao.java

package com.wzq.sample.ui.room_sample;

import java.util.List;

import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;

@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")
    //List<Word> getAllWords();
    LiveData<List<Word>> getAllWordsLive();

}

复制代码

Word.java

package com.wzq.sample.ui.room_sample;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

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

复制代码

看博客要看懂思路即可, 书上得来终觉浅,绝知此事要躬行. 要想清楚如何使用和更高级用法,请clone代码自己查看,才能做到掌握. 项目中用到了Navigation+DataBinding+LilveData+Okhttp+Retrofit+RxJava+Glide.