Android Room 的使用(使用room实现增删改查)

封装了SQlite

第一步:创建数据库表类

package com.example.room;

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

@Entity//一张表
public class Student {
    //主键,自增长
    @PrimaryKey(autoGenerate = true)
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

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

    public Student() {
    }

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

第二步:创建对数据库增删改查的接口

package com.example.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 insertStudent(Student... students);
//有条件删除
@Delete
    void deleteStudent(Student... students);
@Update
    void updateStudent(Student... students);
//查询所有
@Query("select * from student")
    List  getAllStudent();
//有条件查询没有成功
@Query("select * from student where id = :id")
    List getStudentById(int id);
//删除所有
@Query("DELETE FROM Student")
   void deleteAllStudent();
}

第三步:创建数据库操作类,使用他获取到Dao接口中的方法对数据库进行操作,(单例模式)

package com.example.room;


import android.content.Context;

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

//将数据库与Dao相连接
@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;

    //将MyDataBase设置为单例模式
    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();

}

第四步:在主业面调用

package com.example.room;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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

import android.widget.Button;
import android.widget.ListView;

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

public class MainActivity extends AppCompatActivity {
    StudentDao studentDao;
    RecyclerView lv;
    List list;
    Button btInsert,btDelAll,btSelAll,btUpdate,btSelOne,btDelOne;
    Student s1,s2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initview();
        initevent();
        s1 = new Student(1,"jack" ,21);
        s2 = new Student(2,"AA",66);
        list = new ArrayList<>();
        //获取到数据库操作类
        MyDatabase database = MyDatabase.getInstance(this);
        studentDao = database.getStudentDao();
        //设置列表显示
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        lv.setLayoutManager(layoutManager);

    }

    //监听方法
    private void initevent() {
        btInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insert(s1,s2);
            }
        });
        btSelAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                select();

                lv.setAdapter(new MyRecycleAdapter(list,MainActivity.this));
            }
        });
        btDelAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                delall();
            }
        });
        btUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Student sUpdate = new Student("liyuanba",99);
                sUpdate.setId(1);
                update(sUpdate);
            }
        });
        btDelOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                delone(s1);
            }
        });
        btSelOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }

    //初始化方法
    private void initview() {
        btInsert = findViewById(R.id.btInsert);
        btSelAll = findViewById(R.id.btSelAll);
        btDelOne = findViewById(R.id.btdelAll);
        btUpdate = findViewById(R.id.btUpdate);
        btDelAll = findViewById(R.id.btDelOne);
        btSelOne = findViewById(R.id.btSelOne);
        lv = findViewById(R.id.lv);
    }


    //添加
    public void insert(Student...students) {

        new InsertStudentTask(studentDao).execute(students);
    }

    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;
        }
    }



    //查询所有
    public void select() {

    new GetAlltStudentTask(studentDao).execute();
    }

    class GetAlltStudentTask extends AsyncTask{
        private StudentDao studentDao;

        public GetAlltStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }
        @Override
        protected Void doInBackground(Void...voids) {
        list = studentDao.getAllStudent();
        return null;
        }
    }

    //有条件删除
    public void delone(Student...students){

        new DelStudentTesk(studentDao).execute(students);
    }

    class DelStudentTesk extends AsyncTask{
        private StudentDao studentDao;

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

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

    //修改
    public void update(Student...students){

        new UpdateStudentTesk(studentDao).execute(students);
    }

    class UpdateStudentTesk extends AsyncTask{
        private StudentDao studentDao;

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

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

    //删除所有
    public void delall() {

        new GetAlltStudentTask(studentDao).execute();
    }

    class DelAlltStudentTask extends AsyncTask{
        private StudentDao studentDao;

        public DelAlltStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }
        @Override
        protected Void doInBackground(Void...voids) {
              studentDao.deleteAllStudent();
            return null;
        }
    }


}

主页面布局




    

    

    

        

依赖(java的依赖)

    def room_version = "2.2.0-alpha01"
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

你可能感兴趣的:(android,sqlite,java)