Room,数据库框架学习一
Room,数据库框架学习二
接着RoomBasic2项目,当我们对Entity实体类数据结构进行改变时,我们这个时候就需要更新数据库,进行数据的迁移,如在Entity的实体类Word中增加一个private boolean invisible;字段
@Entity
public class Word {
//设置主键自动增长
@PrimaryKey(autoGenerate = true)
private int id;
//字段映射具体的数据表字段名,如果没有定义则用属性名,作为列名。
@ColumnInfo(name = "word")
private String word;
private String chineseMeaning;
private boolean invisible;
//必须指定一个构造方法,room框架需要。并且只能指定一个
//,如果有其他构造方法,则其他的构造方法必须添加@Ignore注解
public Word(String word, String chineseMeaning) {
this.word = word;
this.chineseMeaning = chineseMeaning;
}
//Setter、Getter方法是需要添加的,为了支持room工作
public boolean isInvisible() {
return invisible;
}
public void setInvisible(boolean invisible) {
this.invisible = invisible;
}
。。。
}
1.首先要修改版本号version
2.定义Migration对象(保留数据迁移时),指明数据库的变动迁移具体操作。
3.在数据库对象创建时候添加该Migration对象
.fallbackToDestructiveMigration() 不保留数据,迁移数据
.addMigrations(MIGRATION_3_4)//保留数据迁移
WordDataBase.java
package com.mrlove.roombasic3.dao;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.mrlove.roombasic3.domain.Word;
//配置你要操作的entry类,可以配置一个或者多个,version表名这个是哪个版本,如果升级需要修改的就是这里
@Database(entities = {Word.class}, version = 4) //exportSchema 默认为true,存储展示数据库的结构信息
public abstract class WordDataBase extends RoomDatabase {
//singleton
private static WordDataBase wordDataBase; //单例模式,保证获取的数据库实例是唯一的
public static synchronized WordDataBase getWordDataBase(Context context) {
if (wordDataBase == null) {
wordDataBase = Room.databaseBuilder(context.getApplicationContext(), WordDataBase.class, "word_database")
//下面注释表示允许主线程进行数据库操作,但是不推荐这样做。
//他可能造成主线程lock以及anr
//所以我们的操作都是在新线程完成的
// .allowMainThreadQueries()
//.fallbackToDestructiveMigration() 不保留数据,迁移数据
//保留数据迁移
.addMigrations(MIGRATION_3_4)
.build();
}
return wordDataBase;
}
//RoomDatabase提供直接访问底层数据库实现,我们通过定义抽象方法返回具体Dao
//然后进行数据库增删该查的实现。
public abstract WordDao getWordDao();
//通过此方法,执行database底层sqlite语句进行数据的迁移
static final Migration MIGRATION_1_2 = new Migration(1,2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE word ADD COLUMN version TEXT");
}
};
//sqlite没有字段的删除,所以只能通过数据的父子到新表的方式实现字段的删除
static final Migration MIGRATION_2_3 = new Migration(2,3) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
//首先创建一个新表word_temp,然后把要保留的字段数据填充到新表中,删除旧表,重命名新表名,完成想要数据的迁移
database.execSQL("CREATE TABLE word_temp (id INTEGER PRIMARY KEY NOT NULL ,word TEXT,chineseMeaning TEXT)");
database.execSQL("INSERT INTO word_temp(id,word,chineseMeaning)" +
"SELECT id,word,chineseMeaning FROM word");
database.execSQL("DROP TABLE word");
database.execSQL("ALTER TABLE word_temp RENAME TO word");
}
};
static final Migration MIGRATION_3_4 = new Migration(3,4) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE word ADD COLUMN invisible INTEGER NOT NULL DEFAULT 0");
}
};
}
布局文件的重新设计
注意:RecyclerView的item设置可以点击属性时
设置允许点击android:clickable="true"必须而且仅能在最最外层布局设置允许点击
因为当内部布局设置,而外部没设置时,外部会把内部屏蔽;而当外部设置,内部也设置时,获取点击会聚焦到内部,而实现代码是获取的外部控制逻辑,会导致设置失效,所有只能设置一个在最外面(暂时还不知道更符合逻辑的设置方法)
cell_card2.xml
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<variable
name="data"
type="com.mrlove.roombasic3.MyViewModel" />
</data>
<!--android:clickable="true" 实现元素的可点击,并且只能设置在这里,不能设置在里面的布局上,或者都设置-->
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:clickable="true">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/constraintLayout3"
android:layout_width="0dp"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline6"
app:layout_constraintTop_toTopOf="parent">
<Switch
android:id="@+id/switchbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="10dp"
android:paddingTop="20dp"
android:paddingEnd="10dp"
android:paddingBottom="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/constraintLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.1" />
<TextView
android:id="@+id/textNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline7"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="1" />
<TextView
android:id="@+id/textEnglish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/textEnglish"
android:textSize="24sp"
app:layout_constraintBottom_toTopOf="@+id/textChinese"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.009"
app:layout_constraintStart_toStartOf="@+id/guideline7"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textChinese"
android:layout_width="wrap_content"
android:layout_height="19dp"
android:text="@string/textChinese"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="@+id/textEnglish"
app:layout_constraintTop_toBottomOf="@+id/textEnglish" />
</androidx.constraintlayout.widget.ConstraintLayout>
<View
android:id="@+id/divider"
android:layout_width="2dp"
android:layout_height="match_parent"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="?android:attr/listDivider"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/constraintLayout3"
app:layout_constraintStart_toStartOf="@+id/guideline6"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.85" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
cell_normal2.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="data"
type="com.mrlove.roombasic3.MyViewModel" />
</data>
<!--android:clickable="true" 实现元素的可点击,并且只能设置在这里,不能设置在里面的布局上,或者都设置-->
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true">
<View
android:id="@+id/divider2"
android:layout_width="2dp"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="?android:attr/listDivider"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline5"
app:layout_constraintStart_toStartOf="@+id/guideline5"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toEndOf="@+id/constraintLayout2"
app:layout_constraintTop_toTopOf="parent">
<Switch
android:id="@+id/switchbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="10dp"
android:paddingTop="20dp"
android:paddingEnd="10dp"
android:paddingBottom="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/constraintLayout2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline5"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.1" />
<TextView
android:id="@+id/textNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="1" />
<TextView
android:id="@+id/textEnglish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/textEnglish"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="@+id/guideline4"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="@+id/textChinese"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/textChinese"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="@+id/textEnglish"
app:layout_constraintTop_toBottomOf="@+id/textEnglish" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.85" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
适配器的改动
因为添加了一个隐藏释义开关switch。所以Adapter在进行数据的填充的时候
1.先初始化按钮的点击事件为空
2.再初始化释义以及按钮的状态;
3.设置按钮的点击事件
注意:第一步很重要,因为如果不先置为空,RecyclerView有数据回收重复使用的功能,会导致在页面数据滚出屏幕外,又滚回来时,造成点击事件还存在,从而自动再执行,这样就会让初始化释义以及按钮的状态时与上次设置的状态相反,导致数据混乱。
MyAdapter.java
package com.mrlove.roombasic3;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.mrlove.roombasic3.databinding.CellCard2Binding;
import com.mrlove.roombasic3.databinding.CellNormal2Binding;
import com.mrlove.roombasic3.domain.Word;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
//RecyclerView内容管理器类 泛型参数指定为自己的
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private final static String TAG = "mrloveqin";
private List<Word> allWords = new ArrayList<>();
private boolean useCardView;
private CellNormal2Binding normalBinding;
private CellCard2Binding cardBinding;
private MyViewModel myViewModel;
//返回所有的数据
void setAllWords(List<Word> allWords) {
this.allWords = allWords;
}
//初始化布局标志位,和myViewModel
public MyAdapter(boolean useCardView,MyViewModel myViewModel) {
this.useCardView = useCardView;
this.myViewModel = myViewModel;
}
//当适配器创建的时候调用
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//RecyclerView中调用Databinding,绑定布局,获取binding实例
//根据标识位初始化获取不同的binding
if (useCardView) {
cardBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.cell_card2, parent, false);
//把binding作为参数,返回一个自定义的MyViewHolder
return new MyViewHolder(cardBinding);
} else {
normalBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.cell_normal2, parent, false);
return new MyViewHolder(normalBinding);
}
}
//当调用ViewHolder时响应
@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
//获取当前位置的一行数据
final Word word = allWords.get(position);
//设置数据
holder.textNumber.setText(String.valueOf(position + 1)); //让页面显示从1开始,而不用显示word.getId数据库中实际的位置
holder.textEnglish.setText(word.getWord());
holder.textChinese.setText(word.getChineseMeaning());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Uri uri = Uri.parse("https://m.youdao.com/dict?le=eng&q=" + holder.textEnglish.getText());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
holder.itemView.getContext().startActivity(intent);
}
});
//先初始化按钮的点击事件为空,再初始化释义以及按钮的状态;
//如果不先置为空,RecyclerView有数据回收重复使用的功能,会导致在页面数据滚出屏幕外,
//又滚回来时,造成点击事件还存在,从而自动再执行,这样就会让初始化释义以及按钮的状态时
//与上次设置的状态相反,导致数据混乱。
holder.aSwitch.setOnCheckedChangeListener(null);
//第一次加载时,从数据库提取数据,设置初始状态
if(word.isInvisible()){
holder.textChinese.setVisibility(View.GONE);
holder.aSwitch.setChecked(true);
}else {
holder.textChinese.setVisibility(View.VISIBLE);
holder.aSwitch.setChecked(false);
}
//设置隐藏释义按钮的点击时间
holder.aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
holder.textChinese.setVisibility(View.GONE);
word.setInvisible(true);
myViewModel.updateWords(word);
}
else {
holder.textChinese.setVisibility(View.VISIBLE);
word.setInvisible(false);
myViewModel.updateWords(word);
}
}
});
}
@Override
public int getItemCount() {
//返回一个数据的容量
return allWords.size();
}
//把onCreateViewHolder方法中的binding存起来,可以下次再用。这样做的好处就是不必每次都到布局文件中去拿到你的View,提高了效率。
static class MyViewHolder extends RecyclerView.ViewHolder {
private CellNormal2Binding normalBinding;
private CellCard2Binding cardBinding;
private TextView textNumber, textEnglish, textChinese;
private Switch aSwitch;
//两种参数不同的构造函数初始化不同的布局控件
MyViewHolder(@NotNull CellNormal2Binding binding) {
super(binding.getRoot());
normalBinding = binding;
textNumber = normalBinding.textNumber;
textEnglish = normalBinding.textEnglish;
textChinese = normalBinding.textChinese;
aSwitch = normalBinding.switchbutton;
}
MyViewHolder(@NotNull CellCard2Binding binding) {
super(binding.getRoot());
cardBinding = binding;
textNumber = cardBinding.textNumber;
textEnglish = cardBinding.textEnglish;
textChinese = cardBinding.textChinese;
aSwitch = cardBinding.switchbutton;
}
}
}
Mainactivity的改动
基本没什么改动,但是要注意的是,因为这里有个数据观察者,所以当适配器的数据发生改变时,不仅适配器在做数据的更新,这里再监听到数据改变时也在做数据的更新,所以会导致UI界面数据的重新刷新,造成UI显示有不流畅的效果产生,解决办法:判断适配器当前数据与更新后的数据大小是否发生改变,如果没有发生改变就不刷新数据。
MainActivity.java
package com.mrlove.roombasic3;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.mrlove.roombasic3.databinding.ActivityMainBinding;
import com.mrlove.roombasic3.domain.Word;
import java.util.List;
public class MainActivity extends AppCompatActivity {
MyViewModel myViewModel;
//DatabindingBinding 由框架编译时生成,负责通知界面同步更新(命名方式:xml文件名 + Binding);
ActivityMainBinding binding;
MyAdapter myAdaptercard, myAdapternormal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//DataBindingUtil 将布局文件与Activity关联,生成DatabindingBinding实例binding;
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
//获取ViewModel实例
myViewModel = new ViewModelProvider(this, new SavedStateViewModelFactory(getApplication(), this)).get(MyViewModel.class);
//为布局文件设置源数据
binding.setData(myViewModel);
myAdapternormal = new MyAdapter(false,myViewModel);
myAdaptercard = new MyAdapter(true,myViewModel);
binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
binding.recyclerview.setAdapter(myAdapternormal);
binding.switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
binding.recyclerview.setAdapter(myAdaptercard);
} else {
binding.recyclerview.setAdapter(myAdapternormal);
}
}
});
//为实现LiveData的数据设置观察者,以便当数据改变时通知UI更新数据
myViewModel.getAllWordsLive().observe(this, new Observer<List<Word>>() {
@Override
public void onChanged(List<Word> words) {
int temp = myAdaptercard.getItemCount();
int temp1 = myAdapternormal.getItemCount();
myAdaptercard.setAllWords(words);
myAdapternormal.setAllWords(words);
//当适配当前加载内容与现在数据大小不相等时刷新,这样可以避免在隐藏或开启数据时重复刷新数据造成界面卡顿
if(temp!=words.size()||temp1!=words.size()){
myAdaptercard.notifyDataSetChanged();
myAdapternormal.notifyDataSetChanged();
}
}
});
//添加
binding.buttoninsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Word word1 = new Word("hello", "你好");
Word word2 = new Word("world", "世界");
myViewModel.insertWords(word1, word2);
}
});
//删除所有
binding.buttonclear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myViewModel.clearWords();
}
});
//更新
binding.buttonupdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Word word = new Word("haha", "哈哈");
word.setId(40);
myViewModel.updateWords(word);
}
});
//删除某一项
binding.buttondelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Word word = new Word("haha", "哈哈");
word.setId(40);
myViewModel.deleteWords(word);
}
});
}
}
github参考代码:
https://github.com/Mrlove133481/RoomBasic3