Room+ViewModel+LiveData

Room框架支持的LiveData会自动监听数据库的变化,当数据库发生变化的时候,会调用onChanged函数更新UI 

1.MainActivity

package com.tiger.room2;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private StudentRecyclerViewAdapter adapter;
    private StudentViewModel studentViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView recycleView = findViewById(R.id.recycleView);
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        List<Student> students = new ArrayList<>();
        adapter = new StudentRecyclerViewAdapter(students);
        recycleView.setAdapter(adapter);
        studentViewModel = new ViewModelProvider(this).get(StudentViewModel.class);
        //自动更新,给LiveData 添加监听
        LiveData<List<Student>> listLiveData = studentViewModel.queryAllStudentsLive();
        List<Student> value = listLiveData.getValue();
        if (value==null) {
            Log.d("ning","value is null");
        }else {
            Log.d("ning",value.toString());
        }

        listLiveData.observe(this, new Observer<List<Student>>() {
            @Override
            public void onChanged(List<Student> students) {
                Log.d("ning",listLiveData.getValue().toString());
                adapter.setStudents(students);
                adapter.notifyDataSetChanged();
            }
        });
    }

    public void mInsert(View view) {
        Student jack = new Student("Jack", 20);
        Student rose = new Student("rose", 23);
        studentViewModel.insertStudent(jack, rose);
    }

    public void mDelete(View view) {
        Student student = new Student(1);
        studentViewModel.deleteStudent(student);
    }

    public void mUpdate(View view) {
        Student rose = new Student(3, "wqeqasdaddqweqwe", 212313);
        studentViewModel.updateStudent(rose);
    }

    public void mClear(View view) {
        studentViewModel.deleteAllStudent();
    }

}

2.MyDataBase

package com.tiger.room2;

import android.content.Context;

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

//一定要写成抽象类
@Database(entities = {Student.class}, version = 1, exportSchema = false)
public abstract class MyDataBase extends RoomDatabase {

    private static final String DATABASE_NAME = "my_db.db";
    private static MyDataBase mInstance;


    public static MyDataBase getInstance(Context context){

        if (mInstance == null){
            synchronized(MyDataBase.class){
                if (mInstance == null){
                    mInstance = Room.databaseBuilder(context.getApplicationContext(), MyDataBase.class,DATABASE_NAME)
//                            .allowMainThreadQueries() 允许主线程操作数据库
                            .build();
                }
            }

        }
        return mInstance;
    }

    public abstract StudentDao getStudentDao();//room自动实现

}

3.Student

package com.tiger.room2;

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

@Entity(tableName = "student")
public class Student {

    @PrimaryKey(autoGenerate = true)//主键 自增
    @ColumnInfo(name = "id",typeAffinity = ColumnInfo.INTEGER)//指定列名  类型
    public int id;

    @ColumnInfo(name = "name",typeAffinity = ColumnInfo.TEXT)//指定列名  类型
    public String name;

    @ColumnInfo(name = "age",typeAffinity = ColumnInfo.INTEGER)//指定列名  类型
    public int age;


//    @Ignore
//    public boolean flag; 属性也可以忽略 ,代表它不是数据库的一列

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Ignore //room忽略此构造方法 构造对象
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Ignore
    public Student(int id) {
        this.id = id;
    }


    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

4.StudentDao

package com.tiger.room2;

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

import java.util.List;

@Dao
public interface StudentDao {

    @Insert
    void insert(Student... students);

    @Delete
    void deleteStudent(Student... students);

    @Query("delete from student")
    void deleteAll();

    @Update
    void updateStudent(Student... students);

    @Query("select * from student")
    LiveData<List<Student>> getAllStudentsLive();


    @Query("select * from student where id = :id")
    Student getStudentById(int id);


}

5.StudentRecyclerViewAdapter

package com.tiger.room2;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * @author ningchuanqi
 * @version V1.0
 */
public class StudentRecyclerViewAdapter extends RecyclerView.Adapter {

    List<Student> students;

    public StudentRecyclerViewAdapter(List<Student> students) {
        this.students = students;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
       View root = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
       return new MyViewHoder(root);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Student student = students.get(position);
        TextView tvId = holder.itemView.findViewById(R.id.tvId);
        tvId.setText(String.valueOf(student.id));

        TextView tvName = holder.itemView.findViewById(R.id.tvName);
        tvName.setText(student.name);

        TextView tvAge = holder.itemView.findViewById(R.id.tvAge);
        tvAge.setText(String.valueOf(student.age));
    }

    @Override
    public int getItemCount() {
        return students.size();
    }

    static class MyViewHoder extends RecyclerView.ViewHolder {

        public MyViewHoder(@NonNull View itemView) {
            super(itemView);
        }
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }
}

6.StudentReposity

package com.tiger.room2;

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

import androidx.lifecycle.LiveData;

import java.util.List;

public class StudentRepository {

    private StudentDao studentDao;

    public StudentRepository(Context context) {
        MyDataBase dataBase = MyDataBase.getInstance(context);
        this.studentDao = dataBase.getStudentDao();
    }


    public void insertStudent(Student ... students) {
        new InsertStudentTask(studentDao).execute(students);
    }


    class InsertStudentTask extends AsyncTask<Student, Void, Void> {

        private StudentDao studentDao;

        public InsertStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }

        @Override
        protected Void doInBackground(Student ... students) {
            studentDao.insert(students);
            return null;
        }
    }


    public void updateStudent(Student... students) {
        new UpdateStudentTask(studentDao).execute(students);
    }

    class UpdateStudentTask extends AsyncTask<Student, Void, Void> {

        private StudentDao studentDao;

        public UpdateStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }

        @Override
        protected Void doInBackground(Student... students) {
            studentDao.updateStudent(students);
            return null;
        }
    }

//除非服务器崩了,要不然代码不可能错

    public void deleteStudent(Student ... student) {
        new DeleteStudentTask(studentDao).execute(student);
    }

    class DeleteStudentTask extends AsyncTask<Student, Void, Void> {

        private StudentDao studentDao;

        public DeleteStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }

        @Override
        protected Void doInBackground(Student... students) {
            studentDao.deleteStudent(students);
            return null;
        }
    }

    public void deleteAllStudent() {
        new DeleteAllStudentTask(studentDao).execute();
    }

    class DeleteAllStudentTask extends AsyncTask<Void, Void, Void> {

        private StudentDao studentDao;

        public DeleteAllStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }


        @Override
        protected Void doInBackground(Void... voids) {
            studentDao.deleteAll();
            return null;
        }
    }

    public LiveData<List<Student>> queryAllStudentsLive() {
        return studentDao.getAllStudentsLive();
    }

//    class GetAllStudentTask extends AsyncTask<Void,Void,Void>{
//
//        private StudentDao studentDao;
//
//        public GetAllStudentTask(StudentDao studentDao) {
//            this.studentDao = studentDao;
//        }
//
//        @Override
//        protected Void doInBackground(Void... voids) {
//            List<Student> students = studentDao.getAllStudent();
//            adapter.setStudents(students);
//            return null;
//        }
//
//        @Override
//        protected void onPostExecute(Void aVoid) {
//            super.onPostExecute(aVoid);
//            adapter.notifyDataSetChanged();
//        }
//    }


}

7.StudentViewModel

package com.tiger.room2;

import android.app.Application;

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

import java.util.List;

public class StudentViewModel extends AndroidViewModel {

    private StudentRepository studentRepository;

    public StudentViewModel(@NonNull Application application) {
        super(application);
        this.studentRepository = new StudentRepository(application);
    }

    public void insertStudent(Student ... students){
        studentRepository.insertStudent(students);
    }
    public void deleteStudent(Student ... students){
        studentRepository.deleteStudent(students);
    }
    public void updateStudent(Student ... students){
        studentRepository.updateStudent(students);
    }

    public void deleteAllStudent(){
        studentRepository.deleteAllStudent();
    }

    public LiveData<List<Student>>  queryAllStudentsLive(){
        return studentRepository.queryAllStudentsLive();
    }

}

8.xml

<?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_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.2" />

    <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.5" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.1" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycleView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.709"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline3" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="增加"
        android:onClick="mInsert"
        app:layout_constraintBottom_toTopOf="@+id/guideline5"
        app:layout_constraintEnd_toStartOf="@+id/guideline4"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除"
        android:onClick="mDelete"
        app:layout_constraintBottom_toTopOf="@+id/guideline5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline4"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="修改"
        android:onClick="mUpdate"
        app:layout_constraintBottom_toTopOf="@+id/guideline3"
        app:layout_constraintEnd_toStartOf="@+id/guideline4"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline5" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清空"
        android:onClick="mClear"
        app:layout_constraintBottom_toTopOf="@+id/guideline3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline4"
        app:layout_constraintTop_toTopOf="@+id/guideline5" />
</androidx.constraintlayout.widget.ConstraintLayout>

9.item.xml

<?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_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingVertical="10dip">

    <TextView
        android:id="@+id/tvId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        tools:text="1"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/guideline"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        tools:text="Jack"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        tools:text="18"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline2"
        app:layout_constraintTop_toTopOf="parent" />

    <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.8" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.2" />
</androidx.constraintlayout.widget.ConstraintLayout>

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RoomLiveDataViewModel结合是为了实现数据持久化、数据观察与界面更新的最佳实践。 Room是Google为Android提供的一个持久化数据库解决方案,它简化了数据库操作并提供了编译时检查,同时支持在后台线程中进行数据库访问。LiveData是一种可观察的数据容器,它可以感知生命周期,并在数据变化时自动更新。ViewModel则负责管理界面相关的数据,并且与Activity或Fragment的生命周期无关,避免了数据丢失或重复请求的问题。 将RoomLiveData结合使用,可以将Room中的数据变化以LiveData的形式暴露出来。这样,在数据库发生变化时,LiveData会自动通知相关观察者进行界面更新。LiveData还具有自动清理机制,当观察者的生命周期结束时会自动停止数据的更新,避免了内存泄漏问题。 而结合ViewModel可以更好地管理界面相关的数据。ViewModel可以在配置改变时(如屏幕旋转)保留数据,并且避免了异步任务导致的内存泄漏。通过在ViewModel中缓存LiveData对象,可以在Activity或Fragment恢复时继续观察数据变化,并保持界面更新的一致性。 总结而言,RoomLiveDataViewModel的结合可以实现一个可靠、高效、响应式的数据处理框架,使得数据的持久化、观察与界面更新变得十分简单。这样的架构设计也有利于代码的维护与扩展,提高了开发效率与用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值