您当前的位置: 首页 > 

梁同学与Android

暂无认证

  • 6浏览

    0关注

    618博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Andriod --- JetPack :Room + ViewModel + LiveData 增删改查实例

梁同学与Android 发布时间:2022-03-31 19:40:49 ,浏览量:6

Andriod — JetPack :初识 JetPack

Andriod — JetPack :LifeCycle 的诞生

Andriod — JetPack :ViewModel 的诞生

Andriod — JetPack :BaseObservable 与 ObservableField 双向绑定

Andriod — JetPack :DataBinding + LiveData +ViewModel 简单实例

Andriod — JetPack :Room 增删改查

Andriod — JetPack :Room + ViewModel + LiveData 增删改查实例

Andriod — JetPack :LiveData setValue 和 postValue 的区别

一、前言

1.为什么使用 LiveData + ViewModel ? 每当数据库数据发生变化时,都需要开启一个工作线程去重新获取数据库中的数据。所以,当数据变化时,我们可以通过 LiveData 通知 View 层,实现数据的自动更新。 2.图解 在这里插入图片描述 二、代码实例

build.gradle

// Room
implementation "androidx.room:room-runtime:2.2.5"
annotationProcessor "androidx.room:room-compiler:2.2.5"
implementation 'androidx.recyclerview:recyclerview:1.0.0'

activity_main.xml





    

    

    

    

    

    

    

    

item.xml




    

    


    

    

    

Student.java

package com.example.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;

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

StudentDao.java

package com.example.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 insertStudent(Student... students); // 可以传入多个 Student

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

    @Query("DELETE FROM student")
    void deleteAllStudent();

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

    @Query("SELECT * FROM student")
    LiveData getAllStudentsLive();

    @Query("SELECT * FROM student WHERE id = :id")
    List getStudentById(Integer id);
}

MyDataBase.java

package com.example.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;

    // 构建 database 单例
    public static synchronized MyDataBase getInstance(Context context) {
        if(mInstance == null) {
            mInstance = Room.databaseBuilder(context.getApplicationContext(), MyDataBase.class, DATABASE_NAME)
                    //.allowMainThreadQueries() // 允许在主线程操作数据库
                    .build();
        }
        return mInstance;
    }
    public abstract StudentDao getStudentDao();
}

StudentRepository.java

package com.example.room2;

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

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();
        this.studentDao = studentDao;
    }

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

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

    public void deleteAllStudents() {
        new DeleteAllStudentsTask(studentDao).execute();
    }

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

    public LiveData getAllStudentsLive() {
        return studentDao.getAllStudentsLive();
    }

    // 异步线程添加学生
    class InsertStudentTask extends AsyncTask {
        private StudentDao studentDao;

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

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

    // 异步修改学生
    class UpdateStudentTask extends AsyncTask {
        private StudentDao studentDao;

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

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

    // 异步删除学生
    class DeleteStudentTask extends AsyncTask {
        private StudentDao studentDao;

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

        @Override
        protected Void doInBackground(Student... students) {
            studentDao.deleteStudent(students);
            return null;
        }
    }
    // 异步删除所有学生
    class DeleteAllStudentsTask extends AsyncTask {
        private StudentDao studentDao;

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

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

}

StudentViewModel.java

package com.example.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 repository;

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


    public void insertStudent(Student... students) {
        repository.insertStudent(students);
    }

    public void deleteAllStudents() {
        repository.deleteAllStudents();
    }

    public void deleteStudent(Student... students) {
        repository.deleteStudent(students);
    }

    public void updateStudent(Student... students) {
        repository.updateStudent(students);
    }

    public LiveData getAllStudentsLive() {
        return repository.getAllStudentsLive();
    }


}

MainActivity.java

package com.example.room2;

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

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
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 StudentRecycleViewAdapter adapter;
    private StudentDao studentDao;
    private StudentViewModel studentViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List students = new ArrayList();
        RecyclerView recyclerView = findViewById(R.id.rv_01);

        adapter = new StudentRecycleViewAdapter(students);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        // 得到 ViewModel
        studentViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(StudentViewModel.class);
        // 自动更新操作,给 LiveData 监听
        studentViewModel.getAllStudentsLive().observe(this, new Observer() {
            @Override
            public void onChanged(List students) {
                adapter.setStudents(students);
                adapter.notifyDataSetChanged();
            }
        });
    }
    // Room 不允许在主线程操作数据库,如果非在主线程操作数据库,请修改 MyDataBase 文件

    // 增加
    public void mInsert(View view) {
        Student s1 = new Student("Jack", 20);
        Student s2 = new Student("Rose", 22);
        studentViewModel.insertStudent(s1, s2);
    }

    // 删除
    public void mDelete(View view) {
        Student s1 = new Student(4);
        studentViewModel.deleteStudent(s1);
    }

    // 修改
    public void mUpdate(View view) {
        Student s1 = new Student(3, "Jason", 21);
        studentViewModel.updateStudent(s1);
    }


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

StudentRecycleViewAdapter.java

package com.example.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;

public class StudentRecycleViewAdapter extends RecyclerView.Adapter {

    List students;

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

    public StudentRecycleViewAdapter(List students) {
        this.students = students;
    }

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

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Student student = students.get(position);

        holder.tvId.setText(String.valueOf(student.id));
        holder.name.setText(student.name);
        holder.age.setText(String.valueOf(student.age));
    }

    @Override
    public int getItemCount() {
        return students == null ? 0 :students.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView tvId, name, age;

        public MyViewHolder(View view) {
            super(view);
            tvId = view.findViewById(R.id.tvId);
            name = view.findViewById(R.id.name);
            age = view.findViewById(R.id.age);
        }
    }
}
关注
打赏
1660730345
查看更多评论
立即登录/注册

微信扫码登录

0.0458s