1.学生应用的CRUD
1.导入依赖
//room依赖 API
implementation("androidx.room:room-runtime:2.6.1")
//帮助我们生成一些代码 生成接口的实现类
annotationProcessor("androidx.room:room-compiler:2.6.1")
2.MainActivity
package com.tiger.room;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
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 StudentDao studentDao;
@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);
MyDataBase database = MyDataBase.getInstance(this);
studentDao = database.getStudentDao();
}
public void mInsert(View view) {
Student s1 = new Student("Jack", 20);
Student s2 = new Student("Rose", 18);
new InsertStudentTask(studentDao).execute(s1,s2);
}
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 mDelete(View view) {
Student s1 = new Student(2);
new DeleteStudentTask(studentDao).execute(s1);
}
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 mUpdate(View view) {
Student s1 = new Student(3,"Jason", 21);
new UpdateStudentTask(studentDao).execute(s1);
}
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 mQuery(View view) {
new GetAllStudentTask(studentDao).execute();
}
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();
}
}
}
3.Entity
package com.tiger.room;
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;
}
}
4.Dao
package com.tiger.room;
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);
@Update
void updateStudent(Student...students);
@Query("select * from student")
List<Student> getAllStudent();
@Query("select * from student where id = :id")
Student getStudentById(int id);
}
5.MyDataBase
package com.tiger.room;
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自动实现
}
6.adapter
package com.tiger.room;
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;
}
}
7.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="mQuery"
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>
<?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>