Jetpack是一套库、工具和指南,可以帮助开发者更轻松地编写优质应用。这些组件可以帮助开发者遵循最佳做法、
让开发者摆脱编写样板代码的工作并简化复杂任务,以便开发者将精力集中放在所需的代码上。
(1)Architecture(架构组件)可帮助您设计稳健、可测试且易维护的应用
一直以来,解藕都是软件开发永恒的话题。在Android开发中,解藕很大程度上表现为系统组件的生命周期与普通组件之间的解藕,因为普通组件在使用过程中需要依赖系统组件的的生命周期。
举个例子,我们经常需要在页面的onCreate()方法中对组件进行初始化,然后在onStop()中停止组件,或者在onDestory()方法中对进行进行销毁。事实上,这样的工作非常繁琐,会让页面和页面耦合度变高,但又不得不做,因为如果不即时的释放资源,有可能会导致内存泄露。例如,下面是一个在Activity的同生命周期方法中监听调用的例子,代码如下。
public class MyListener {
private static final String TAG = "MyListener";
public void start(){
Log.d(TAG, "start: ");
}
public void stop(){
Log.d(TAG, "stop: ");
}
public void resume(){
Log.d(TAG, "resume: ");
}
}
public class LifecycleActivity extends AppCompatActivity {
private MyListener mMyListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lifecycle);
mMyListener = new MyListener();
mMyListener.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
mMyListener.stop();
}
}
虽然,代码看起来没什么问题,但在实际开发中可能会有多个组件在Activity的生命周期中进行回调,这样Activity的生命周期的方法中可能就需要编写大量的代码,这就使得它们难以维护。 我们希望在对组件进行管理不依赖页面的生命周期的回调方法,同时当页面生命周期发生改变时,也能够即时的收到通知。这在Android组件化和架构设计的时候表现的尤为明显。
那纠结什么是Lifecycle组件呢?总的来说,Lifecycle 就是具有生命周期感知能力的组件。简单的理解就是,当Activity/Fragment的生命周期产生变化时,Lifecycle组件会感应相应的生命周期变化,当然我们还可以通过使用Lifecycle组件来在自定义的类中管理Activity/fragment的生命周期。
目前,Lifecycle生命周期组件主要由Lifecycle、LifecycleOwner、LifecycleObserver三个对象构成。
(1)Lifecycle:是一个持有组件生命周期状态与事件(如Activity或Fragment)的信息的类。
(2)LifecycleOwner:Lifecycle的提供者,通过实现LifecycleOwner接口来访问Lifecycle生命周期对象。
Fragment和FragmentActivity类实现了LifecycleOwner接口,它具有访问生命周期的getLifecycle方法,使用时
需要在自己的类中实现LifecycleOwner。
(3)LifecycleObserver:Lifecycle观察者,可以使用LifecycleOwner类的addObserver()方法进行注册,被注册后
LifecycleObserver便可以观察到LifecycleOwner的生命周期事件。
(1)依赖:
def lifecycle_version = "2.5.1"
implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version")
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
(2)按照Lifecycle的使用流程,需要先定义观察者,并重写对应的生命周期:设计模式:观察者模式
public class MyObserver implements LifecycleObserver {
private static final String TAG = "MyObserver";
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void start(){
Log.d(TAG, "start: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void stop(){
Log.d(TAG, "stop: ");
}
}
(3)activity
public class LifecycleActivity2 extends AppCompatActivity {
private MyObserver mMyObserver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lifecycle2);
mMyObserver = new MyObserver();
getLifecycle().addObserver(mMyObserver);
}
}
当activity关闭的时候,dialog没有关闭,进而导致内存泄漏,下面使用lifecycle打造一个完美的dialog
(1)自定义dialog并实现LifecycleObserver接口
public class MyDiaLog extends Dialog implements LifecycleObserver {
public MyDiaLog(@NonNull Context context) {
super(context);
}
public MyDiaLog(@NonNull Context context, int themeResId) {
super(context, themeResId);
}
protected MyDiaLog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_dialog);
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void destory(){
dismiss();
}
}
(2)activity
public class DialogActivity extends AppCompatActivity {
private MyDiaLog mMyDiaLog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
mMyDiaLog = new MyDiaLog(this);
getLifecycle().addObserver(mMyDiaLog);
mMyDiaLog.show();
}
}
举例:一般项项目获得用户的位置需要在Service中监听,当Service被创建的时候需要注册监听,当Service销毁的时候需要解除注册,不然很造成内存泄漏现象(常见的内存泄漏现象可以上网多了解下)
a.自定义LifecycleObserver类,service创建的时候注册监听,service销毁的时候解除注册监听
public class MyLocationObserver implements LifecycleObserver {
private Context context;
private LocationManager locationManager;
private MyLocationListener locationListener;
public MyLocationObserver(Context context) {
this.context = context;
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
private void startGetLocation() {
Log.d("ning","startGetLocation");
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, locationListener);
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
private void stopGetLocation() {
Log.d("ning","stopGetLocation");
locationManager.removeUpdates(locationListener);
}
static class MyLocationListener implements LocationListener{
@Override
public void onLocationChanged(Location location) {
Log.d("ning","location changed:"+location.toString());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
}
b。Service:继承LifecycleService
public class MyLocationService extends LifecycleService {
public MyLocationService() {
Log.d("ning","MyLocationService");
MyLocationObserver observer = new MyLocationObserver(this);
getLifecycle().addObserver(observer);
}
}
c。activity启动服务和停止服务
public class Step3Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_two);
}
public void startGps(View view) {
startService(new Intent(this,MyLocationService.class));
}
public void stopGps(View view) {
stopService(new Intent(this,MyLocationService.class));
}
}
d。权限以及动态权限,此处省略
a。自定义LifecycleObserver类
public class ApplicationObserver implements LifecycleObserver {
private String TAG = "ning";
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.d(TAG, "Lifecycle.Event.ON_CREATE");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Log.d(TAG, "Lifecycle.Event.ON_START");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.d(TAG, "Lifecycle.Event.ON_RESUME");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.d(TAG, "Lifecycle.Event.ON_PAUSE");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.d(TAG, "Lifecycle.Event.ON_STOP");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.d(TAG, "Lifecycle.Event.ON_DESTROY");
}
}
b。application添加观察者
public class MyApplication extends Application{
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle()
.addObserver(new ApplicationObserver());
}
}
ViewModel 同样具有生命周期意识的处理跟UI相关的数据,并且,当设备的一些配置信息改变(例如屏幕旋转)它的数据不会消失。
通常情况下,如果我们不做特殊处理,当屏幕旋转的时候,数据会消失,那 ViewModel 管理的数据为什么不会消失呢,是因为 ViewModel 的生命周期:
注意:不要向ViewModel中传入Context,会导致内存泄漏,如果使用Context请使用AndroidViewModel的Appliction
案例:当屏幕方向发生改变的时候,数据保持不变
(1)自定义ViewModel
public class NumViewModel extends ViewModel {
public int num;
}
(2)activity实现,并旋转屏幕测试
public class ViewModelActivity extends AppCompatActivity {
private TextView tv;
private NumViewModel numViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_model);
tv = findViewById(R.id.tv);
//获得viewmodel,页面切换后数据不变
numViewModel = new ViewModelProvider(this).get(NumViewModel.class);
tv.setText(numViewModel.num+"");
}
public void plus(View view) {
tv.setText(numViewModel.num+++"");
}
}
public class MyAndriodViewModel extends AndroidViewModel {
public int num;
public MyAndriodViewModel(@NonNull Application application) {
super(application);
}
}
public class AndrodiViewModelActivity extends AppCompatActivity {
private TextView tv;
private MyAndriodViewModel mAndroidViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_androdi_view_model);
tv = findViewById(R.id.tv);
mAndroidViewModel = new ViewModelProvider(this).get(MyAndriodViewModel.class);
tv.setText(mAndroidViewModel.num);
}
public void plus(View view) {
tv.setText(mAndroidViewModel.num+++"");
}
}
public class FragmentViewModel extends ViewModel {
public int num;
}
public class OneFragment extends Fragment {
private Button bt;
private View view;
private FragmentViewModel fragmentViewModel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one, container, false);
bt = view.findViewById(R.id.tv);
fragmentViewModel = new ViewModelProvider(getActivity()).get(FragmentViewModel.class);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragmentViewModel.num++;
bt.setText(fragmentViewModel.num+"");
}
});
return view;
}
}
public class TwoFragment extends Fragment {
private Button bt;
private View view;
private FragmentViewModel fragmentViewModel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_two, container, false);
bt = view.findViewById(R.id.tv);
fragmentViewModel = new ViewModelProvider(getActivity()).get(FragmentViewModel.class);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragmentViewModel.num++;
bt.setText(fragmentViewModel.num+"");
}
});
return view;
}
}
在讲 LiveData 之前,我们先看看 LiveData 和 ViewModel 的作用
从官网的介绍可以看到, LiveData 作用跟RxJava类似,是观察数据的类,相比RxJava,它能够在Activity、Fragment和Service之中正确的处理生命周期。那么 LiveData 有什么优点呢?
- 数据变更的时候更新UI
- 没有内存泄漏
- 不会因为停止Activity崩溃
- 无需手动处理生命周期
- 共享资源
乍看之下 LiveData 挺鸡肋的,事实也确实如此,因为 LiveData 能够实现的功能 RxJava 也可以实现,而且与LiveData 相比, RxJava 拥有着更加丰富的生态,当然,谷歌的官方架构仍然值得我们去学习。
(1)自定义ViewModel并定义MutableLiveData变量
public class MyViewModel extends ViewModel {
private MutableLiveData<Integer> progress;
public MutableLiveData<Integer> getProgress() {
if(progress == null){
progress = new MutableLiveData<>();
progress.setValue(0);
}
return progress;
}
}
(2)activity代码:定时器不断修改数据,liveData观察数据变化并更新UI
public class LiveDataActivity extends AppCompatActivity {
private MyViewModel viewModel;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
textView.setText(String.valueOf(viewModel.getCurrentSecond().getValue()));
/*****观察数据变化更新UI******/
viewModel.getCurrentSecond().observe(this, new Observer<Integer>() {
@Override
public void onChanged(Integer i) {
textView.setText(String.valueOf(i));
}
});
startTimer();
}
private void startTimer() {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
//修改数据
//非UI线程 postValue
//UI线程 setValue
viewModel.getCurrentSecond().postValue(viewModel.getCurrentSecond().getValue()+1);
}
},1000,1000);
}
}
2个fragment,第二个fragment进度条发生改变,第一个fragment值实时更新
MVVM(全称Model-View-ViewModel)同 MVC 和 MVP 一样,是逻辑分层解偶的模式
Data Binding 不算特别新的东西,2015年Google就推出了,但即便是现在,很多人都没有学习过它,我就是这些工程师中的一位,因为我觉得MVP已经足够帮我处理日常的业务, Android Jetpack 的出现,是我研究 Data Binding 的一个契机。
在进行下文之前,我有必要声明一下,MVVM和Data Binding是两个不同的概念,MVVM是一种架构模式,而Data Binding是一个实现数据和UI绑定的框架,是构建MVVM模式的一个工具。
(1)app gradle配置
android {
//....
dataBinding {
enabled true
}
}
(2)xml布局,在根标签快捷键选择第一个
自动生成 databinding 布局文件
databing标签介绍
(3)User类:
public class User {
private String username;//用户名
private int age;//年龄
private boolean show;//是否显示
private String imageUrl;//图片
public User(String username, int age, String imageUrl) {
this.username = username;
this.age = age;
this.imageUrl = imageUrl;
}
public boolean isShow() {
return show;
}
public void setShow(boolean show) {
this.show = show;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public User(String username, int age, boolean show, String imageUrl) {
this.username = username;
this.age = age;
this.show = show;
this.imageUrl = imageUrl;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User(String username, int age) {
this.username = username;
this.age = age;
}
}
(4)activity布局
<?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="user"
type="com.bawei.jetpackforjava.databing.User" />
<import type="android.view.View"></import>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".databing.DataBingActivityOne">
<EditText
android:text="@{user.username}"
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"></EditText>
<EditText
android:text='@{user.age+""}'
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"></EditText>
<ImageView
android:background="@color/black"
android:visibility="@{user.show ? View.VISIBLE :View.GONE}"
android:id="@+id/iv"
android:layout_width="80dp"
android:layout_height="80dp"></ImageView>
<Button
android:id="@+id/bt_login"
android:text="修改"
android:layout_width="match_parent"
android:layout_height="wrap_content"></Button>
</LinearLayout>
</layout>
(5)activity代码:
public class DataBingActivityOne extends AppCompatActivity {
private ActivityDataBingOneBinding mActivityDataBingOneBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_bing_one);
mActivityDataBingOneBinding = DataBindingUtil.setContentView(this,R.layout.activity_data_bing_one);
User user = new User("张三", 3,true,"");
mActivityDataBingOneBinding.setUser(user);
}
}
思考问题:DataBind中如何显示图片
(1)ImageViewBinderAdapter:图片适配器
public class ImageViewBinderAdapter {
//加载网络图片
@BindingAdapter("image")
public static void setImage(ImageView imageView, String url){
if(!TextUtils.isEmpty(url)){
Glide.with(imageView.getContext())//这里上下文建议使用application,避免内存泄漏
.load(url)
.placeholder(R.drawable.ic_launcher_background)
.into(imageView);
}else{
imageView.setBackgroundColor(Color.GRAY);
}
}
//加载本地图片
@BindingAdapter("image")
public static void setImage(ImageView imageView, int resId){
imageView.setImageResource(resId);
}
//参数可选,网络图片为空时,加载本地图片
@BindingAdapter(value = {"image", "defaultImageResource"}, requireAll = false)
public static void setImage(ImageView imageView, String url, int resId){
if(!TextUtils.isEmpty(url)){
Glide.with(imageView.getContext())这里上下文建议使用application,避免内存泄漏
.load(url)
.placeholder(R.drawable.ic_launcher_background)
.into(imageView);
}else{
imageView.setImageResource(resId);
}
}
}
(2)布局文件中设置image属性引用图片地址
<ImageView
image="@{user.imageUrl}"
android:background="@color/black"
android:visibility="@{user.show ? View.VISIBLE :View.GONE}"
android:id="@+id/iv"
android:layout_width="80dp"
android:layout_height="80dp"></ImageView>
(1)User实体类:
public class User {
private String username;//用户名
private String caption;//描述
private String imageUrl;//图片
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public User(String username, String caption, String imageUrl) {
this.username = username;
this.caption = caption;
this.imageUrl = imageUrl;
}
}
<?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="user"
type="com.bawei.jetpackforjava.databing_recyclerview.User" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingVertical="10dip">
<ImageView
android:id="@+id/imageView"
android:layout_width="100dip"
android:layout_height="100dip"
image="@{user.imageUrl}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline2"
app:layout_constraintHorizontal_bias="0.432"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.054"
tools:srcCompat="@tools:sample/avatars" />
<TextView
android:id="@+id/textViewChName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.username}"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.138"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.063"
tools:text="斯嘉丽.约翰逊" />
<TextView
android:id="@+id/textViewEnName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
android:text='@{user.caption}'
android:textSize="18sp"
app:layout_constraintStart_toStartOf="@+id/textViewChName"
app:layout_constraintTop_toBottomOf="@+id/textViewChName"
tools:text="Scarlett Johansson" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.4" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
(3)ImageViewBinderAdapter
public class ImageViewBinderAdapter {
//加载网络图片
@BindingAdapter("image")
public static void setImage(ImageView imageView, String url){
if(!TextUtils.isEmpty(url)){
Glide.with(imageView.getContext())//这里上下文建议使用application,避免内存泄漏
.load(url)
.placeholder(R.drawable.ic_launcher_background)
.into(imageView);
}else{
imageView.setBackgroundColor(Color.GRAY);
}
}
//加载本地图片
@BindingAdapter("image")
public static void setImage(ImageView imageView, int resId){
imageView.setImageResource(resId);
}
//参数可选,网络图片为空时,加载本地图片
@BindingAdapter(value = {"image", "defaultImageResource"}, requireAll = false)
public static void setImage(ImageView imageView, String url, int resId){
if(!TextUtils.isEmpty(url)){
Glide.with(imageView.getContext())这里上下文建议使用application,避免内存泄漏
.load(url)
.placeholder(R.drawable.ic_launcher_background)
.into(imageView);
}else{
imageView.setImageResource(resId);
}
}
}
(4)适配器
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private List<User> mUserList;
public RecyclerViewAdapter(List<User> userList) {
mUserList = userList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ItemBinding itemBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),R.layout.item,parent,false);
return new MyViewHolder(itemBinding);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
User user = mUserList.get(position);
holder.mItemBinding.setUser(user);
}
@Override
public int getItemCount() {
return mUserList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
ItemBinding mItemBinding;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
}
public MyViewHolder(ItemBinding itemBinding) {
super(itemBinding.getRoot());
this.mItemBinding = itemBinding;
}
}
}
(5)activity
public class RecyclerViewActivity extends AppCompatActivity {
private ActivityRecyclerViewBinding viewDataBinding;
private RecyclerViewAdapter mRecyclerViewAdapter;
private List<User> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_recycler_view);
initData();
mRecyclerViewAdapter = new RecyclerViewAdapter(list);
viewDataBinding.rv.setAdapter(mRecyclerViewAdapter);
viewDataBinding.rv.setLayoutManager(new LinearLayoutManager(this));
}
private void initData() {
User i1 = new User("斯嘉丽.约翰逊","Scarlett Johansson","https://5b0988e595225.cdn.sohucs.com/images/20190624/d93dbf866aa2405f8b9b1d660c15db9d.jpeg");
list.add(i1);
User i2 = new User("安吉丽娜·朱莉","Angelina Jolie","https://5b0988e595225.cdn.sohucs.com/images/20190624/0657ccc0066b4e1797ead2b3293230b0.jpeg");
list.add(i2);
User i3 = new User("杰西卡·辛普森","Jessica Simpson","https://5b0988e595225.cdn.sohucs.com/images/20190624/49c95e9b542a4854b2232e67579b9215.jpeg");
list.add(i3);
User i4 = new User("萨尔玛·海耶克","Salma Hayek","https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3893590240,2013198505&fm=26&gp=0.jpg");
list.add(i4);
User i5 = new User("卡门·伊莱克特拉","Carmen Electra","https://5b0988e595225.cdn.sohucs.com/images/20190624/1399d0fda46c467dbd988f2996dccaad.jpeg");
list.add(i5);
User i6 = new User("凯瑟琳·海格尔","Katherine Heigl","https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fq_70%2Cc_zoom%2Cw_640%2Fimages%2F20180116%2F74c81a087a28446590734ca257e3eacf.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1618118692&t=6c5c1eecb1b0db8664810bfc51f8609b");
list.add(i6);
User i7 = new User("珍妮佛·安妮斯顿","Jennifer Aniston","https://5b0988e595225.cdn.sohucs.com/images/20190624/98e8b18a86004eb79bef58318e93446d.jpeg");
list.add(i7);
User i8 = new User("梅根·福克斯","Megan Fox","https://5b0988e595225.cdn.sohucs.com/images/20190624/37991ee797e6496d99cdee5315082b76.jpeg");
list.add(i8);
User i9 = new User("杰西卡·阿尔芭","Jessica Alba","https://5b0988e595225.cdn.sohucs.com/images/20190624/eb49bf15b9634d579ff89f596c54e0ca.jpeg");
list.add(i9);
User i10 = new User("詹妮弗·洛芙·休伊特","Jennifer Love Hewitt","https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=791729948,2390587761&fm=26&gp=0.jpg");
list.add(i10);
}
}
Room 是一个持久性库,属于 Android Jetpack 的一部分。Room 是 SQLite 数据库之上的一个抽象层。Room 并不直接使用 SQLite,而是负责简化数据库设置和配置以及与数据库交互方面的琐碎工作。此外,Room 还提供 SQLite 语句的编译时检查
**数据实体(Entity)**表示应用的数据库中的表。数据实体用于更新表中的行所存储的数据以及创建新行供插入。
数据访问对象 (DAO) 提供应用在数据库中检索、更新、插入和删除数据所用的方法。
**数据库类(Database)**持有数据库,并且是应用数据库底层连接的主要访问点。数据库类为应用提供与该数据库关联的 DAO 的实例。
使用编译时注解,能够对 @Query 和 @Entity 里面的SQL语句等进行验证。
与SQL语句的使用更加贴近,能够降低学习成本。
对 RxJava 2 的支持(大部分都Android数据库框架都支持),对 LiveData 的支持。
@Embedded 能够减少表的创建。
依赖:
def room_version = "2.4.0"
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor("androidx.room:room-compiler:$room_version")
// To use Kotlin annotation processing tool (kapt)
// To use Kotlin Symbol Processing (KSP)
// ksp("androidx.room:room-compiler:$room_version")
// optional - Kotlin Extensions and Coroutines support for Room
implementation("androidx.room:room-ktx:$room_version")
// optional - RxJava2 support for Room
implementation("androidx.room:room-rxjava2:$room_version")
// optional - Paging 3 Integration
implementation("androidx.room:room-paging:$room_version")
defaultConfig里面配置:这里注意一定是+=不是= ,后面会介绍
javaCompileOptions {
annotationProcessorOptions {
//room的数据库概要、记录
arguments += ["room.schemaLocation":
"$projectDir/schemas".toString()]
}
}
@Entity(tableName = "student")
public class Student {
@PrimaryKey(autoGenerate = true)//主键自增
@ColumnInfo(name = "id", typeAffinity = ColumnInfo.INTEGER)
private long id;
@ColumnInfo(name = "username", typeAffinity = ColumnInfo.TEXT)
private String username;
@ColumnInfo(name = "age", typeAffinity = ColumnInfo.INTEGER)
private int age;
public Student(long id, String username, int age) {
this.id = id;
this.username = username;
this.age = age;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@Dao
public interface StudentDao {
//添加一条数据
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Student student);
//添加多条数据
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(List<Student> students);
//删除一条数据
@Delete
void delete(Student student);
//删除多条数据
@Delete
void deleteList(List<Student> students);
//删除所有数据
@Query("delete from Student")
void deleteAll();
//修改数据
@Update
void update(Student student);
//查询所有
@Query("select * from student")
List<Student> getAllStudents();
//根据姓名查找
@Query("select * from student where username = :username ")
List<Student> getStudentByName(String username);
}
/**
* entities:数据表实体类
* version:版本号
* exportSchema:是否导出Schema文件
*/
@Database(entities = {Student.class},version = 2,exportSchema = true)
public abstract class AppDataBase extends RoomDatabase {
public static final String DB_NAME = "StudentDatabase.db";//数据库名称
//注意构造不能私有化
private static AppDataBase appDataBase;
public static AppDataBase getInstance(){
if(appDataBase == null){
synchronized (AppDataBase.class){
appDataBase = Room.databaseBuilder(App.instance,AppDataBase.class,DB_NAME)
.allowMainThreadQueries()数据库耗时操作,默认不能在主线程执行
.build();
}
}
return appDataBase;
}
private StudentDao studentDao;
public abstract StudentDao getStudentDao();
}
public class RoomActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room);
List<Student> list = new ArrayList<>();
Student student1 = new Student(1,"张三1",18);
Student student2 = new Student(2,"张三2",28);
Student student3 = new Student(3,"张三3",38);
Student student4 = new Student(4,"张三4",48);
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
AppDataBase.getInstance().getStudentDao().insert(list);
student2.setUsername("李四");
AppDataBase.getInstance().getStudentDao().update(student2);
AppDataBase.getInstance().getStudentDao().delete(student2);
List<Student> allStudents = AppDataBase.getInstance().getStudentDao().getAllStudents();
List<Student> lisi = AppDataBase.getInstance().getStudentDao().getStudentByName("李四");
}
}
如果直接将数据库版本升级到4,却没有写对应的Migration,则会出现IllegalStateException异常
第一种,直接添加fallbackToDestructiveMigration方法,该方法在出现异常时,重建数据表同时数据会丢失,不建议
第二种,写出对应的版本升级Migration,Room 会判断当前有没有直接1到4的升级方案,如果有,直接执行1到4的升级方案,如果没有,Room就会按照顺序执行Migration(1,2)、Migration(2,3)、Migration(3,4)已完成升级
/**
* entities:数据表实体类
* version:版本号
* exportSchema:是否导出Schema文件
*/
@Database(entities = {Student.class},version = 2,exportSchema = true)
public abstract class AppDataBase extends RoomDatabase {
public static final String DB_NAME = "StudentDatabase.db";//数据库名称
//注意构造不能私有化
private static AppDataBase appDataBase;
public static AppDataBase getInstance(){
if(appDataBase == null){
synchronized (AppDataBase.class){
appDataBase = Room.databaseBuilder(App.instance,AppDataBase.class,DB_NAME)
.allowMainThreadQueries()//数据库耗时操作,默认不能在主线程执行
.addMigrations(MIGRATION_1_2)//数据库升级
.addMigrations(MIGRATION_2_3)//数据库升级
// .fallbackToDestructiveMigration()//表重新建立,数据销毁,
.build();
}
}
return appDataBase;
}
private StudentDao studentDao;
public abstract StudentDao getStudentDao();
//1->2:增加sex字段
static final Migration MIGRATION_1_2 = new Migration(1,2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE student ADD COLUMN sex INTEGER NOT NULL DEFAULT 1");
}
};
//2->3:销毁与重建策略
static final Migration MIGRATION_2_3 = new Migration(2,3) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE temp_student (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"+
"name TEXT,"+
"age INTEGER NOT NULL,"+
"sex TEXT DEFAULT 'M',"+
"bar_data INTEGER NOT NULL DEFAULT 1)");
database.execSQL("INSERT INTO temp_student (name,age,sex,bar_data)" +
"SELECT name,age,sex,bar_data FROM student");
database.execSQL("DROP TABLE student");
database.execSQL("ALTER TABLE temp_student RENAME TO student");
}
};
}
@Entity(tableName = "student")
public class Student {
@PrimaryKey(autoGenerate = true)//主键自增
@ColumnInfo(name = "id", typeAffinity = ColumnInfo.INTEGER)
private long id;
@ColumnInfo(name = "username", typeAffinity = ColumnInfo.TEXT)
private String username;
@ColumnInfo(name = "age", typeAffinity = ColumnInfo.INTEGER)
private int age;
//V2.0
@ColumnInfo(name = "sex", typeAffinity = ColumnInfo.INTEGER)
public int sex;
//V4.0
/*@ColumnInfo(name = "sex", typeAffinity = ColumnInfo.TEXT)
public String sex;*/
public Student(long id, String username, int age) {
this.id = id;
this.username = username;
this.age = age;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static AppDataBase getInstance(){
if(appDataBase == null){
synchronized (AppDataBase.class){
appDataBase = Room.databaseBuilder(App.instance,AppDataBase.class,DB_NAME)
.allowMainThreadQueries()//数据库耗时操作,默认不能在主线程执行
.addMigrations(MIGRATION_1_2)//数据库升级
.addMigrations(MIGRATION_2_3)//数据库升级
// .fallbackToDestructiveMigration()//表重新建立,数据销毁,
.createFromAsset("xxx.db")//从assets目录中预填充数据
.createFromFile(new File("xxx.db"))//从sdcard目录中预填充数据
.build();
}
}
return appDataBase;
}