赞
踩
Android Room 是 Android 官方提供的一个持久性库,用于在 Android 应用程序中管理数据库。它提供了一个简单的 API 层,使得使用 SQLite 数据库变得更加容易和方便。
以下是 Android Room 的主要特点:
总之,Android Room 是一个功能强大的持久性库,使得管理 SQLite 数据库变得更加简单和方便。它提供了一个对象关系映射层、事务管理、数据库抽象等功能,可以帮助您更轻松地构建和管理 Android 应用程序中的数据库。
使用教程: Room | Jetpack | Android Developers
开发文档:androidx.room | Android Developers
- dependencies {
-
- //Room
- def room_version = "2.5.0"
- implementation "androidx.room:room-runtime:$room_version"
- annotationProcessor "androidx.room:room-compiler:$room_version"
- }
- package com.example.myroom.entity;
-
- import androidx.room.ColumnInfo;
- import androidx.room.Entity;
- import androidx.room.PrimaryKey;
-
- //实体类 表名 不写默认内名首字母小写 people
- @Entity(tableName = "people")
- public class People {
- //主键 自动生成
- @PrimaryKey(autoGenerate = true)
- private int id;
-
- //列的名称
- @ColumnInfo(name = "user_name")
- private String name;
-
- //不写默认列的名称为age,sex
- private int age;
- private String sex;
-
- public People(String name, int age, String sex) {
- this.name = name;
- this.age = age;
- this.sex = sex;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public int getId() {
- return 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 String getSex() {
- return sex;
- }
-
- public void setSex(String sex) {
- this.sex = sex;
- }
- }
- package com.example.myroom.dao;
-
- import androidx.room.Dao;
- import androidx.room.Delete;
- import androidx.room.Insert;
- import androidx.room.Query;
- import androidx.room.Update;
-
- import com.example.myroom.entity.People;
-
- import java.util.List;
-
- //dao database access object 接口 处理数据库的方法签名
- @Dao
- public interface PeopleDao {
-
- //添加 传递一个参数 对象
- @Insert
- void insertDataOne(People people);
-
- //添加 可以传递多个参数 对象
- @Insert
- void insertDataS(People... people);
-
- //删除
- @Delete
- int deleteDataS(People... people);
-
- //修改 传入对象 设置 id 进行修改某一个
- @Update
- int updateData(People... people);
-
- //查询 根据id倒序
- @Query("select * from people order by id desc")
- List<People> getPeoples();
-
- //根据id查询
- @Query("select * from people where id =:numb")
- People getPeople(Integer numb);
-
- //删除表数据
- @Query("delete from people")
- void deleteTableData();
-
- }
4.写个抽象类继承RoodDatabase
- package com.example.myroom.dao;
-
- import androidx.room.Database;
- import androidx.room.RoomDatabase;
-
- import com.example.myroom.entity.People;
-
- //抽象类 继承 RoomDatabase 我们不用实现people中的方法
- // version = 1 数据库版本,exportSchema = false不允许导出数据库的架构
- @Database(entities = {People.class}, version = 1, exportSchema = false)
- public abstract class PeopleDataBase extends RoomDatabase {
- /**
- * Java 抽象类的一些特点
- * 不能被实例化:抽象类不能被实例化,因为它没有具体的实现细节。它只能被继承,并且子类必须实现抽象类中的所有抽象方法。
- * 包含抽象方法:抽象类可以包含抽象方法,这些方法只有声明但没有实现。子类必须实现这些抽象方法,否则它也必须被声明为抽象类。
- * 提供通用功能和行为:抽象类提供了一些通用功能和行为,这些功能和行为可以被其子类继承和重用。子类可以根据需要扩展这些功能和行为,或者重写它们以提供不同的实现。
- * 用于设计高层次的抽象:抽象类可以用于表示一个高层次的抽象概念或者一个通用模板,使得代码更加模块化和可维护。通过将一些公共方法和行为提取到一个抽象类中,可以避免在多个子类中重复实现相同的功能。
- * 扩展性:抽象类可以定义一些扩展的接口,子类可以选择实现这些接口来提供额外的功能。这使得抽象类具有很好的扩展性,可以根据需要添加新的功能和行为
- */
-
- /*
- public abstract PeopleDao peopleDao();
- }
- package com.example.myroom;
-
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
-
- import androidx.appcompat.app.AppCompatActivity;
- import androidx.room.Room;
-
- import com.example.myroom.dao.PeopleDao;
- import com.example.myroom.dao.PeopleDataBase;
- import com.example.myroom.entity.People;
-
- import java.util.List;
-
- public class MainActivity extends AppCompatActivity {
-
- PeopleDataBase DB;
- private Button btnInsert, btnDelete, btnUpdate, btnSelect, btnDeleteData;
- private TextView textContent;
- private EditText etName, etAge, etSex, etSelect, etDelete, etUpdate;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- DB = Room.databaseBuilder(this, PeopleDataBase.class, "peopleDB")
- // 默认不允许在主线程中连接数据库 强制在主线程中处理
- .allowMainThreadQueries()
- .build();
- textContent = findViewById(R.id.tvcontent);
- etName = findViewById(R.id.etName);
- etAge = findViewById(R.id.etAge);
- etSex = findViewById(R.id.etSex);
- etSelect = findViewById(R.id.etSelect);
- etDelete = findViewById(R.id.etDelete);
- etUpdate = findViewById(R.id.etUpdate);
-
- btnInsert = findViewById(R.id.btnSave);
- btnDelete = findViewById(R.id.btnDelete);
- btnUpdate = findViewById(R.id.btnUpdate);
- btnSelect = findViewById(R.id.btnselect);
- btnDeleteData = findViewById(R.id.btnDeleteTB);
-
- //查询数据
- selectData(null);
-
- //按钮事件 插入数据
- btnInsert.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- //插入数据 防止空
- String name = etName.getText().toString().equals("") ? "张三" : etName.getText().toString();
- int age = etAge.getText().toString().equals("") ? 20 : Integer.parseInt(etAge.getText().toString());
- String sex = etSex.getText().toString().equals("") ? "男" : etSex.getText().toString();
- People people = new People(name, age, sex);
- DB.peopleDao().insertDataS(people);
- //查询数据
- selectData(null);
-
- }
- });
-
- //修改数据
- btnUpdate.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- //修改
- int id = etUpdate.getText().toString().equals("") ? 0 : Integer.parseInt(etUpdate.getText().toString());
- if (id != 0) {
- String name = etName.getText().toString();
- int age = Integer.parseInt(etAge.getText().toString());
- String sex = etSex.getText().toString();
- People people = new People(name, age, sex);
- people.setId(id);
- DB.peopleDao().updateData(people);
- //查询
- selectData(null);
- }
-
- }
- });
-
- //删除
- btnDelete.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- int id = etDelete.getText().toString().equals("") ? 0 : Integer.parseInt(etDelete.getText().toString());
- if (id != 0) {
- People people = new People();
- people.setId(id);
- DB.peopleDao().deleteDataS(people);
- //查询
- selectData(null);
- }
-
- }
- });
-
- //根据id 查数据
- btnSelect.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- int id = etSelect.getText().toString().equals("") ? 0 : Integer.parseInt(etSelect.getText().toString());
- if (id != 0) {
- selectData(id);
- }
-
- }
- });
-
- //删除全部数据
- btnDeleteData.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- DB.peopleDao().deleteTableData();
- }
- });
-
- }
-
- /**
- * 查询数据的方法
- */
- public void selectData(Integer id) {
- try {
- StringBuilder text = new StringBuilder();
- if (id == null || id == 0) {
- List<People> peopleList = DB.peopleDao().getPeoples();
- if (peopleList.size() != 0) {
- for (int i = 0; i < peopleList.size(); i++) {
- People people = peopleList.get(i);
- text.append("id:")
- .append(people.getId())
- .append("---name:")
- .append(people.getName())
- .append("---age:")
- .append(people.getAge())
- .append("---sex:")
- .append(people.getSex())
- .append("\n");
- }
- } else {
- text.append("没有可用的数据");
- }
-
- } else {
- People people = DB.peopleDao().getPeople(id);
- text.append("id:")
- .append(people.getId())
- .append("---name:")
- .append(people.getName())
- .append("---age:")
- .append(people.getAge())
- .append("---sex:")
- .append(people.getSex());
- }
-
- textContent.setText(text.toString());
-
- } catch (Exception e) {
- Log.e("TAG", "----查询失败------------" + e.getMessage());
- }
-
-
- }
-
- }
- <?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">
-
- <Button
- android:id="@+id/btnUpdate"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="修改"
- app:layout_constraintBottom_toBottomOf="@+id/etUpdate"
- app:layout_constraintEnd_toStartOf="@+id/guideline10"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toEndOf="@+id/etUpdate"
- app:layout_constraintTop_toTopOf="@+id/etUpdate"
- app:layout_constraintVertical_bias="0.0" />
-
- <androidx.constraintlayout.widget.Guideline
- android:id="@+id/guideline2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal"
- app:layout_constraintGuide_percent="0.05" />
-
- <TextView
- android:id="@+id/textView"
- android:layout_width="match_parent"
- android:layout_height="0dp"
- android:text="Room简单应用:"
- android:textSize="24sp"
- app:layout_constraintBottom_toTopOf="@+id/guideline2"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
-
- <Button
- android:id="@+id/btnSave"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="4dp"
- android:text="保存"
- app:layout_constraintBottom_toTopOf="@+id/guideline9"
- app:layout_constraintEnd_toStartOf="@+id/guideline10"
- app:layout_constraintHorizontal_bias="0.203"
- app:layout_constraintStart_toStartOf="@+id/guideline5"
- app:layout_constraintTop_toTopOf="@+id/guideline4" />
-
- <Button
- android:id="@+id/btnDelete"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="删除"
- app:layout_constraintBottom_toBottomOf="@+id/etDelete"
- app:layout_constraintEnd_toStartOf="@+id/guideline10"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toEndOf="@+id/etDelete"
- app:layout_constraintTop_toTopOf="@+id/etDelete" />
-
- <Button
- android:id="@+id/btnselect"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="查询"
- app:layout_constraintBottom_toBottomOf="@+id/etSelect"
- app:layout_constraintEnd_toStartOf="@+id/guideline10"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toEndOf="@+id/etSelect"
- app:layout_constraintTop_toTopOf="@+id/etSelect" />
-
- <Button
- android:id="@+id/btnDeleteTB"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="4dp"
- android:text="删除表数据"
- app:layout_constraintBottom_toTopOf="@+id/guideline9"
- app:layout_constraintEnd_toStartOf="@+id/guideline10"
- app:layout_constraintHorizontal_bias="0.873"
- app:layout_constraintStart_toStartOf="@+id/guideline5"
- app:layout_constraintTop_toTopOf="@+id/guideline4" />
-
- <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.13" />
-
- <androidx.constraintlayout.widget.Guideline
- android:id="@+id/guideline4"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal"
- app:layout_constraintGuide_percent="0.29548565" />
-
- <TextView
- android:id="@+id/textView2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="姓名:"
- android:textSize="24sp"
- app:layout_constraintBottom_toTopOf="@+id/guideline3"
- app:layout_constraintEnd_toStartOf="@+id/etName"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toStartOf="@+id/guideline5" />
-
- <EditText
- android:id="@+id/etName"
- android:layout_width="200dp"
- android:layout_height="wrap_content"
- android:ems="10"
- android:hint="请输入"
- android:inputType="text"
- app:layout_constraintBottom_toBottomOf="@+id/textView2"
- app:layout_constraintEnd_toStartOf="@+id/guideline10"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toEndOf="@+id/textView2"
- app:layout_constraintTop_toTopOf="@+id/textView2" />
-
- <androidx.constraintlayout.widget.Guideline
- android:id="@+id/guideline5"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- app:layout_constraintGuide_percent="0.05352798" />
-
- <androidx.constraintlayout.widget.Guideline
- android:id="@+id/guideline6"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal"
- app:layout_constraintGuide_percent="0.21" />
-
- <androidx.constraintlayout.widget.Guideline
- android:id="@+id/guideline8"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal"
- app:layout_constraintGuide_percent="0.6" />
-
- <androidx.constraintlayout.widget.Guideline
- android:id="@+id/guideline9"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal"
- app:layout_constraintGuide_percent="0.37" />
-
- <TextView
- android:id="@+id/textView3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="性别:"
- android:textSize="24sp"
- app:layout_constraintBottom_toTopOf="@+id/guideline6"
- app:layout_constraintEnd_toStartOf="@+id/etSex"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toStartOf="@+id/guideline5" />
-
- <EditText
- android:id="@+id/etSex"
- android:layout_width="200dp"
- android:layout_height="wrap_content"
- android:ems="10"
- android:hint="请输入"
- android:inputType="text"
- app:layout_constraintBottom_toBottomOf="@+id/textView3"
- app:layout_constraintEnd_toStartOf="@+id/guideline10"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toEndOf="@+id/textView3"
- app:layout_constraintTop_toTopOf="@+id/textView3" />
-
- <EditText
- android:id="@+id/etAge"
- android:layout_width="200dp"
- android:layout_height="wrap_content"
- android:ems="10"
- android:hint="请输入"
- android:inputType="number"
- app:layout_constraintBottom_toBottomOf="@+id/textView4"
- app:layout_constraintEnd_toStartOf="@+id/guideline10"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toEndOf="@+id/textView4"
- app:layout_constraintTop_toTopOf="@+id/textView4" />
-
- <TextView
- android:id="@+id/textView4"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="年龄:"
- android:textSize="24sp"
- app:layout_constraintBottom_toTopOf="@+id/guideline4"
- app:layout_constraintEnd_toStartOf="@+id/etAge"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toStartOf="@+id/guideline5" />
-
- <androidx.constraintlayout.widget.Guideline
- android:id="@+id/guideline10"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- app:layout_constraintGuide_percent="0.9" />
-
- <EditText
- android:id="@+id/etSelect"
- android:layout_width="100dp"
- android:layout_height="wrap_content"
- android:ems="10"
- android:hint="请输入id"
- android:inputType="number"
- app:layout_constraintBottom_toTopOf="@+id/guideline8"
- app:layout_constraintEnd_toStartOf="@+id/btnselect"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toStartOf="@+id/guideline5"
- app:layout_constraintTop_toTopOf="@+id/guideline9"
- app:layout_constraintVertical_bias="0.0" />
-
- <EditText
- android:id="@+id/etDelete"
- android:layout_width="100dp"
- android:layout_height="wrap_content"
- android:ems="10"
- android:hint="请输入id"
- android:inputType="number"
- app:layout_constraintBottom_toTopOf="@+id/guideline8"
- app:layout_constraintEnd_toStartOf="@+id/btnDelete"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toStartOf="@+id/guideline5"
- app:layout_constraintTop_toTopOf="@+id/guideline9"
- app:layout_constraintVertical_bias="0.451" />
-
- <EditText
- android:id="@+id/etUpdate"
- android:layout_width="100dp"
- android:layout_height="wrap_content"
- android:ems="10"
- android:hint="请输入id"
- android:inputType="number"
- app:layout_constraintBottom_toTopOf="@+id/guideline8"
- app:layout_constraintEnd_toStartOf="@+id/btnUpdate"
- app:layout_constraintHorizontal_bias="0.5"
- app:layout_constraintStart_toStartOf="@+id/guideline5"
- app:layout_constraintTop_toTopOf="@+id/etSelect"
- app:layout_constraintVertical_bias="1.0" />
-
- <TextView
- android:id="@+id/tvcontent"
- android:layout_width="0dp"
- android:layout_height="0dp"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toStartOf="@+id/guideline10"
- app:layout_constraintStart_toStartOf="@+id/guideline5"
- app:layout_constraintTop_toTopOf="@+id/guideline8"
- tools:hint="这里显示数据" />
-
- </androidx.constraintlayout.widget.ConstraintLayout>
示例图:
数据库:
把这三个文件导出查看数据库:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。