Room----Android数据库(SQLite)

博观而约取,厚积而薄发。这篇文章主要讲述Room----Android数据库(SQLite)相关的知识,希望能为你提供帮助。
1.要想使用Room首先需要在build.grade中添加依赖

1dependencies { 2def room_version = "2.2.2" 3 4implementation "androidx.room:room-runtime:$room_version" 5annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor 6 7// optional - Kotlin Extensions and Coroutines support for Room 8implementation "androidx.room:room-ktx:$room_version" 9 10// optional - Rxjava support for Room 11implementation "androidx.room:room-rxjava2:$room_version" 12 13// optional - Guava support for Room, including Optional and ListenableFuture 14implementation "androidx.room:room-guava:$room_version" 15 16// Test helpers 17testImplementation "androidx.room:room-testing:$room_version" 18} 19

 
2.数据库可视化工具可以选择DB Browser for SQLite,具体请点击下方链接进行下载
http://www.sqlitebrowser.org/
 
具体案例(对Word实体进行增删改)使用ViewModel,LiveData,Room等工具。
 
1.界面设计
  • 上方是一个ScrollView(数据多的时候可滑动),ScrollView内有一个TextView
  • 下方是四个按键,分别代表,插入、删除、清空、修改
activity_main.xml代码如下:
Room----Android数据库(SQLite)

文章图片
Room----Android数据库(SQLite)

文章图片
1 < ?xml version="1.0" encoding="utf-8"?> 2 < androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3xmlns:app="http://schemas.android.com/apk/res-auto" 4xmlns:tools="http://schemas.android.com/tools" 5android:layout_width="match_parent" 6android:layout_height="match_parent" 7tools:context=".MainActivity"> 8 9< androidx.constraintlayout.widget.Guideline 10android:id="@+id/guideline" 11android:layout_width="wrap_content" 12android:layout_height="wrap_content" 13android:orientation="horizontal" 14app:layout_constraintGuide_percent="0.6" /> 15 16< ScrollView 17android:layout_width="0dp" 18android:layout_height="0dp" 19app:layout_constraintBottom_toTopOf="@+id/guideline" 20app:layout_constraintEnd_toEndOf="parent" 21app:layout_constraintStart_toStartOf="parent" 22app:layout_constraintTop_toTopOf="parent"> 23 24< TextView 25android:id="@+id/textView" 26android:layout_width="match_parent" 27android:layout_height="wrap_content" 28android:text="TextView" 29android:textSize="24sp" /> 30< /ScrollView> 31 32< Button 33android:id="@+id/buttonInsert" 34android:layout_width="wrap_content" 35android:layout_height="wrap_content" 36android:text="insert" 37app:layout_constraintBottom_toBottomOf="parent" 38app:layout_constraintEnd_toStartOf="@+id/buttonUpdate" 39app:layout_constraintHorizontal_bias="0.5" 40app:layout_constraintStart_toStartOf="parent" 41app:layout_constraintTop_toTopOf="@+id/guideline" 42app:layout_constraintVertical_bias="0.25" /> 43 44< Button 45android:id="@+id/buttonUpdate" 46android:layout_width="wrap_content" 47android:layout_height="wrap_content" 48android:text="update" 49app:layout_constraintBottom_toBottomOf="@+id/buttonInsert" 50app:layout_constraintEnd_toEndOf="parent" 51app:layout_constraintHorizontal_bias="0.5" 52app:layout_constraintStart_toEndOf="@+id/buttonInsert" 53app:layout_constraintTop_toTopOf="@+id/buttonInsert" /> 54 55< Button 56android:id="@+id/buttonClear" 57android:layout_width="wrap_content" 58android:layout_height="wrap_content" 59android:text="clear" 60app:layout_constraintBottom_toBottomOf="@+id/buttonDelete" 61app:layout_constraintEnd_toStartOf="@+id/buttonDelete" 62app:layout_constraintHorizontal_bias="0.5" 63app:layout_constraintStart_toStartOf="parent" 64app:layout_constraintTop_toTopOf="@+id/buttonDelete" /> 65 66< Button 67android:id="@+id/buttonDelete" 68android:layout_width="wrap_content" 69android:layout_height="wrap_content" 70android:text="delete" 71app:layout_constraintBottom_toBottomOf="parent" 72app:layout_constraintEnd_toEndOf="parent" 73app:layout_constraintHorizontal_bias="0.5" 74app:layout_constraintStart_toEndOf="@+id/buttonClear" 75app:layout_constraintTop_toBottomOf="@+id/buttonUpdate" /> 76 < /androidx.constraintlayout.widget.ConstraintLayout>

View Code以为是学习新的知识,所以不是太注重规定,导致 一些地方写的不是很规范。
 
【Room----Android数据库(SQLite)】2.创建实体(Entity)
1 package com.example.roombasic; 2 3 import androidx.room.ColumnInfo; 4 import androidx.room.Entity; 5 import androidx.room.PrimaryKey; 6 7 @Entity 8 public class Word { 9@PrimaryKey(autoGenerate = true) 10private int id; 11@ColumnInfo(name = "english_word") 12private String word; 13@ColumnInfo(name = "chinese_meaning") 14private String chineseMeaning; 15 16public Word(String word, String chineseMeaning) { 17this.word = word; 18this.chineseMeaning = chineseMeaning; 19} 20 21public int getId() { 22return id; 23} 24 25public void setId(int id) { 26this.id = id; 27} 28 29public String getWord() { 30return word; 31} 32 33public void setWord(String word) { 34this.word = word; 35} 36 37public String getChineseMeaning() { 38return chineseMeaning; 39} 40 41public void setChineseMeaning(String chineseMeaning) { 42this.chineseMeaning = chineseMeaning; 43} 44 }

 
3.创建Dao
1 package com.example.roombasic; 2 3 import androidx.lifecycle.LiveData; 4 import androidx.room.Dao; 5 import androidx.room.Delete; 6 import androidx.room.Insert; 7 import androidx.room.Query; 8 import androidx.room.Update; 9 10 import java.util.List; 11 12 @Dao 13 public interface WordDao { 14@Insert 15void insertWords(Word... words); 16 17@Update 18void updateWords(Word... words); 19 20@Delete 21void deleteWords(Word... words); 22 23@Query("DElETE FROM WORD") 24void deleteAllWords(); 25 26@Query("SELECT * FROM WORD ORDER BY ID DESC ") 27LiveData< List< Word> > getAllWordsLive(); 28 }

 
4.创建database
1 package com.example.roombasic; 2 3 import android.content.Context; 4 5 import androidx.room.Database; 6 import androidx.room.Room; 7 import androidx.room.RoomDatabase; 8 9 @Database(entities = {Word.class}, version = 1, exportSchema = false) 10 public abstract class WordDataBase extends RoomDatabase { 11private static WordDataBase INSTANCE; 12 13static synchronized WordDataBase getDatabase(Context context) { 14if (INSTANCE == null) { 15INSTANCE = Room.databaseBuilder(context.getApplicationContext(), WordDataBase.class, "word_database").build(); 16} 17return INSTANCE; 18} 19public abstract WordDao getWordDao(); 20 }

 
5.创建ViewModel绑定数据
1 package com.example.roombasic; 2 3 import android.app.Application; 4 import android.os.AsyncTask; 5 6 import androidx.annotation.NonNull; 7 import androidx.lifecycle.AndroidViewModel; 8 import androidx.lifecycle.LiveData; 9 10 import java.util.List; 11 12 public class WordViewModel extends AndroidViewModel { 13private WordDao wordDao; 14private LiveData< List< Word> > allWordsLive; 15 16public WordViewModel(@NonNull Application application) { 17super(application); 18WordDataBase wordDataBase = WordDataBase.getDatabase(application); 19wordDao = wordDataBase.getWordDao(); 20allWordsLive = wordDao.getAllWordsLive(); 21} 22 23public LiveData< List< Word> > getAllWordsLive() { 24return allWordsLive; 25} 26 27void insertWords(Word... words) { 28new InsertAsyncTask(wordDao).execute(words); 29} 30 31void updateWords(Word... words) { 32new UpdateAsyncTask(wordDao).execute(words); 33} 34 35void deleteWords(Word... words) { 36new DeleteAsyncTask(wordDao).execute(words); 37} 38 39void deleteAllWords(Word... words) { 40new DeleteAllAsyncTask(wordDao).execute(); 41} 42 43static class InsertAsyncTask extends AsyncTask< Word, Void, Void> { 44private WordDao wordDao; 45 46public InsertAsyncTask(WordDao wordDao) { 47this.wordDao = wordDao; 48} 49 50@Override 51protected Void doInBackground(Word... words) { 52wordDao.insertWords(words); 53return null; 54} 55} 56 57static class UpdateAsyncTask extends AsyncTask< Word, Void, Void> { 58private WordDao wordDao; 59 60public UpdateAsyncTask(WordDao wordDao) { 61this.wordDao = wordDao; 62} 63 64@Override 65protected Void doInBackground(Word... words) { 66wordDao.updateWords(words); 67return null; 68} 69} 70 71static class DeleteAsyncTask extends AsyncTask< Word, Void, Void> { 72private WordDao wordDao; 73 74public DeleteAsyncTask(WordDao wordDao) { 75this.wordDao = wordDao; 76} 77 78@Override 79protected Void doInBackground(Word... words) { 80wordDao.deleteWords(words); 81return null; 82} 83} 84 85static class DeleteAllAsyncTask extends AsyncTask< Void, Void, Void> { 86private WordDao wordDao; 87 88public DeleteAllAsyncTask(WordDao wordDao) { 89this.wordDao = wordDao; 90} 91 92@Override 93protected Void doInBackground(Void... voids) { 94wordDao.deleteAllWords(); 95return null; 96} 97} 98 }

 
6.在MainActivity.java中添加按键监听
1 package com.example.roombasic; 2 3 import android.os.Bundle; 4 import android.view.View; 5 import android.widget.Button; 6 import android.widget.TextView; 7 8 import androidx.appcompat.app.AppCompatActivity; 9 import androidx.lifecycle.Observer; 10 import androidx.lifecycle.ViewModelProviders; 11 12 import java.util.List; 13 14 public class MainActivity extends AppCompatActivity { 15TextView textView; 16Button buttonInsert, buttonDelete, buttonUpdate, buttonClear; 17WordViewModel wordViewModel; 18 19@Override 20protected void onCreate(Bundle savedInstanceState) { 21super.onCreate(savedInstanceState); 22setContentView(R.layout.activity_main); 23wordViewModel = ViewModelProviders.of(this).get(WordViewModel.class); 24textView = findViewById(R.id.textView); 25wordViewModel.getAllWordsLive().observe(this, new Observer< List< Word> > () { 26@Override 27public void onChanged(List< Word> words) { 28StringBuilder text = new StringBuilder(); 29for (int i = 0; i < words.size(); i++) { 30Word word = words.get(i); 31text.append(word.getId()).append(":").append(word.getWord()).append("=").append(word.getChineseMeaning()).append(" "); 32} 33textView.setText(text.toString()); 34} 35}); 36 37buttonInsert = findViewById(R.id.buttonInsert); 38buttonClear = findViewById(R.id.buttonClear); 39buttonDelete = findViewById(R.id.buttonDelete); 40buttonUpdate = findViewById(R.id.buttonUpdate); 41 42buttonInsert.setOnClickListener(new View.OnClickListener() { 43@Override 44public void onClick(View v) { 45Word word1 = new Word("Hello", "你好!"); 46Word word2 = new Word("World", "世界!"); 47wordViewModel.insertWords(word1,word2); 48} 49}); 50 51buttonClear.setOnClickListener(new View.OnClickListener() { 52@Override 53public void onClick(View v) { 54wordViewModel.deleteAllWords(); 55} 56}); 57 58buttonUpdate.setOnClickListener(new View.OnClickListener() { 59@Override 60public void onClick(View v) { 61Word word = new Word("Hi", "你好啊!"); 62word.setId(9); 63wordViewModel.updateWords(word); 64} 65}); 66 67buttonDelete.setOnClickListener(new View.OnClickListener() { 68@Override 69public void onClick(View v) { 70Word word = new Word("Hi", "你好啊!"); 71word.setId(7); 72wordViewModel.deleteWords(word); 73} 74}); 75} 76 }

该实例中修改与删除使用主键进行的,以后会进行修改与完善 。
暂时只学习了一点皮毛,后续会增加一些新的内容。

    推荐阅读