Jetpack -- Room使用简介

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jetpack -- Room使用简介相关的知识,希望对你有一定的参考价值。


简介

  • Room是对 android中SqlLite数据库的一个抽象,实现了流畅的访问SqlLite数据库

基本使用

  • 创建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(String word, String chineseMeaning)
this.word = word;
this.chineseMeaning = chineseMeaning;


public int getId()
return id;


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


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


public String getWord()
return word;


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


public String getChineseMeaning()
return chineseMeaning;

  • 创建Dao
/**
* Description: 访问数据库操作的接口,CRUD操作
*/
@Dao
public interface WordDao
// 系统会帮助我们生成代码
@Insert
void insertWord(Word... words);


@Update
int updateWord(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
// 四个参数,第一个多个entities可以使用逗号隔开, 版本号添加新的字段或者其他更改数据库结构的操作需要更改版本号
@Database(entities = Word.class, version = 1, exportSchema = false)
public abstract class WordDataBase extends RoomDatabase
public abstract WordDao getWordDao();
  • 在Activity中使用
<?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_
android:layout_
tools:context=".MainActivity">


<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_
android:layout_
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.6" />


<ScrollView
android:layout_
android:layout_
app:layout_constraintBottom_toTopOf="@+id/guideline"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">


<TextView
android:id="@+id/textView"
android:layout_
android:layout_
android:text="TextView"
android:textSize="24sp" />
</ScrollView>


<Button
android:id="@+id/buttonInsert"
android:layout_
android:layout_
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="Insert"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/buttonUpdate"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline"
app:layout_constraintVertical_bias="0.26999998" />


<Button
android:id="@+id/buttonUpdate"
android:layout_
android:layout_
android:text="update"
app:layout_constraintBottom_toBottomOf="@+id/buttonInsert"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/buttonInsert"
app:layout_constraintTop_toTopOf="@+id/buttonInsert" />


<Button
android:id="@+id/buttonClear"
android:layout_
android:layout_
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="clear"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/buttonDelete"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/buttonInsert" />


<Button
android:id="@+id/buttonDelete"
android:layout_
android:layout_
android:text="delete"
app:layout_constraintBottom_toBottomOf="@+id/buttonClear"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/buttonClear"
app:layout_constraintTop_toTopOf="@+id/buttonClear" />
</androidx.constraintlayout.widget.ConstraintLayout>
class WordActivity : AppCompatActivity() 
private lateinit var mWordDataBase: WordDataBase
private lateinit var mWordDao: WordDao
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_word)
mWordDataBase = Room.databaseBuilder(this, WordDataBase::class.java, "word data base")
.allowMainThreadQueries()
.build()
mWordDao = mWordDataBase.wordDao


updateView()


buttonInsert.setOnClickListener(
var newWord1 = Word("Hello", "你好")
var newWord2 = Word("World", "世界")
mWordDao.insertWord(newWord1, newWord2)
updateView()
)


buttonClear.setOnClickListener(
mWordDao.deleteAllWords()
)


buttonUpdate.setOnClickListener(
var newWord3 = Word("Hi", "你好!")
newWord3.id = 46
mWordDao.updateWord(newWord3)
updateView()
)


buttonDelete.setOnClickListener(
var newWord4 = Word("Hi", "你好!")
newWord4.id = 46
mWordDao.deleteWords(newWord4)
updateView()
)



private fun updateView()
var list = mWordDao.getAllWords()
var text : String = ""
for(word in list)
text += word.id.toString() + ":"+ word.word + "=" +word.chineseMeaning

textView.text = text

结合ViewModel来使用

  • 实体类我们不做修改
  • Dao将返回全部数据膝盖为LiveData
@Query("SELECT * FROM WORD ORDER BY ID DESC")
LiveData<List<Word>> getAllWords();
  • 数据库的创建我们使用单例模式
// 四个参数,第一个多个entities可以使用逗号隔开, 版本号添加新的字段或者其他更改数据库结构的操作需要更改版本号
@Database(entities = Word.class, version = 1, exportSchema = false)
public abstract class WordDataBase extends RoomDatabase
private static WordDataBase INSTANCE;


static WordDataBase getDatabase(Context context)
if (INSTANCE == null)
synchronized (WordDataBase.class)
if (INSTANCE == null)
INSTANCE = Room.databaseBuilder(context.getApplicationContext(), WordDataBase.class, "word database")
.build();



return INSTANCE;



public abstract WordDao getWordDao();
  • 然后将Activity中的对数据的CRUD放到repository中
class WordRepository(context: Context) 
val mAllWordLive: LiveData<List<Word?>?>?
private val mWordDao: WordDao
init
val wordDataBase = WordDataBase.getDatabase(context.applicationContext)
mWordDao = wordDataBase!!.wordDao!!
mAllWordLive = mWordDao.allWords


fun insertWords(vararg words: Word)
InsertAsyncTask(mWordDao).execute(*words)


fun updateWords(vararg words: Word)
UpdateAsyncTask(mWordDao).execute(*words)


fun deleteWords(vararg words: Word)
DeleteAsyncTask(mWordDao).execute(*words)


fun deleteAllWords()
DeleteAllAsyncTask(mWordDao).execute()


internal class InsertAsyncTask(private val mWordDao: WordDao) : AsyncTask<Word?, Void?, Void?>()
override fun doInBackground(vararg params: Word?): Void?
mWordDao.insertWord(*params)
return null



internal class DeleteAsyncTask(private val mWordDao: WordDao) : AsyncTask<Word?, Void?, Void?>()
override fun doInBackground(vararg params: Word?): Void?
mWordDao.deleteWords(*params)
return null



internal class DeleteAllAsyncTask(private val mWordDao: WordDao) : AsyncTask<Void?, Void?, Void?>()
override fun doInBackground(vararg params: Void?): Void?
mWordDao.deleteAllWords()
return null





internal class UpdateAsyncTask(private val mWordDao: WordDao) : AsyncTask<Word?, Void?, Void?>()
override fun doInBackground(vararg params: Word?): Void?
mWordDao.updateWord(*params)
return null


  • ViewModel中保留数据操作的接口方法
class WordViewModel(application: Application) : AndroidViewModel(application) 
private var mWordRepository: WordRepository
var mAllWordLive: LiveData<List<Word?>?>?

init
mWordRepository = WordRepository(application.applicationContext)
mAllWordLive = mWordRepository.mAllWordLive


fun insertWords(vararg words: Word)
mWordRepository.insertWords(*words)


fun updateWords(vararg words: Word)
mWordRepository.updateWords(*words)


fun deleteWords(vararg words: Word)
mWordRepository.deleteWords(*words)


fun deleteAllWords()
mWordRepository.deleteAllWords()

  • Activity
class WordActivity : AppCompatActivity() 
private lateinit var mWordViewModel: WordViewModel
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_word)
mWordViewModel = ViewModelProviders.of(this).get(WordViewModel::class.java)
mWordViewModel.mAllWordLive!!.observe(this, Observer data ->
data.let
var text: String = ""
for (word in it!!)
text += word!!.id.toString() + ":" + word.word + "=" + word.chineseMeaning

textView.text = text

)

buttonInsert.setOnClickListener
var newWord1 = Word("Hello", "你好")
var newWord2 = Word("World", "世界")
mWordViewModel.insertWords(newWord1, newWord2)


buttonClear.setOnClickListener
mWordViewModel.deleteAllWords()


buttonUpdate.setOnClickListener
var newWord3 = Word("Hi", "你好!")
newWord3.id = 46
mWordViewModel.updateWords(newWord3)


buttonDelete.setOnClickListener
var newWord4 = Word("Hi", "你好!")
newWord4.id = 46
mWordViewModel.deleteWords(newWord4)



以上是关于Jetpack -- Room使用简介的主要内容,如果未能解决你的问题,请参考以下文章

Android Jetpack ROOM 的Dao返回LiveData<Bean>封装及Bean普通的区别

Android jetpack room的使用

Android Jetpack Paging 3:带 Room 的 PagingSource

Android Jetpack简介

JetPack架构---ORM数据库Room的使用

Android jetpack的Paging和Room结合使用