本文主要是介绍Jetpack Room,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
增删改查实战代码
1.先导入依赖
val roomVersion ="2.6.1"implementation("androidx.room:room-runtime:$roomVersion")annotationProcessor("androidx.room:room-compiler:$roomVersion")
2.创建实体类
package com.tiger.chapter06.entity;import androidx.room.Entity;
import androidx.room.PrimaryKey;@Entity//标注实体类 自动生成一些代码
public class BookInfo {@PrimaryKey(autoGenerate = true) //private Integer id;private String name; // 书籍名称private String author; // 作者private String press; // 出版社private Double price; // 价格public BookInfo() {}public BookInfo(Integer id, String name, String author, String press, Double price) {this.id = id;this.name = name;this.author = author;this.press = press;this.price = price;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public String getPress() {return press;}public void setPress(String press) {this.press = press;}public Double getPrice() {return price;}public void setPrice(Double price) {this.price = price;}@Overridepublic String toString() {return "BookInfo{" +"id=" + id +", name='" + name + '\'' +", author='" + author + '\'' +", press='" + press + '\'' +", price=" + price +'}';}
}
3.创建Dao层接口
package com.tiger.chapter06.dao;import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;import com.tiger.chapter06.entity.BookInfo;import java.util.List;@Dao
public interface BookInfoDao {@Insertvoid insert(BookInfo...book);@Query("delete from BookInfo")void deleteAll();@Deletevoid delete(BookInfo...book);@Updateint update(BookInfo...book);@Query("select * from BookInfo")List<BookInfo> queryAll();@Query("select * from BookInfo where name = :name order by id desc limit 1")BookInfo queryByName(String name);}
4.创建抽象数据库类
package com.tiger.chapter06.database;import androidx.room.Database;
import androidx.room.RoomDatabase;import com.tiger.chapter06.dao.BookInfoDao;
import com.tiger.chapter06.entity.BookInfo;//entities 表示该数据库有哪些表,version表示数据库的版本号
//exportSchema 表示是否导出数据库信息的json串,建议设为false,若设为true 还需指定json文件的保存路径
@Database(entities = {BookInfo.class},version = 1,exportSchema = true)
public abstract class BookDataBase extends RoomDatabase {//获取该数据库中某张表的持久化对象public abstract BookInfoDao bookInfoDao();}
5.buile.gradle.kts 开启 exportSchema存储位置
javaCompileOptions {annotationProcessorOptions {argument("room.schemaLocation","$projectDir/schemas".toString())//指定数据库导出的位置}}
6. 在Application里声明 单例实例
package com.tiger.chapter06;import android.app.Application;
import android.content.res.Configuration;
import android.util.Log;import androidx.annotation.NonNull;
import androidx.room.Room;import com.tiger.chapter06.dao.BookInfoDao;
import com.tiger.chapter06.database.BookDataBase;import java.util.HashMap;public class MyApplication extends Application {private static MyApplication mApp;public static MyApplication getInstance(){return mApp;}public HashMap<String,String> infoMap = new HashMap<>();//声明一个书籍数据库对象private BookDataBase bookDataBase;//在App启动时调用@Overridepublic void onCreate() {super.onCreate();mApp=this;Log.d("ning"," MyApplication onCreate");// 构建书籍数据库的实例bookDataBase = Room.databaseBuilder(this,BookDataBase.class,"book")//允许迁移数据库(发生数据库变更时,Room默认删除原数据库再创建新数据库。如此一来原来的记录会丢失,故而要改为迁移方式以便保存原有记录).addMigrations()//允许在主线程中操作数据库(Room默认不能在主线程中操作数据库).allowMainThreadQueries().build();}//在App终止时调用@Overridepublic void onTerminate() {super.onTerminate();Log.d("ning","onTerminate");}//在配置改变时调用,例如从竖屏变为横屏@Overridepublic void onConfigurationChanged(@NonNull Configuration newConfig) {super.onConfigurationChanged(newConfig);Log.d("ning","onConfigurationChanged");}//获取书籍数据库的实例public BookDataBase getBookDB(){return bookDataBase;}}
7.在Activity执行onCreate方法 将 Application的实例对象 放入此对象中, 实现增删改查
package com.tiger.chapter06;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;import com.tiger.chapter06.dao.BookInfoDao;
import com.tiger.chapter06.entity.BookInfo;
import com.tiger.chapter06.utils.ToastUtlis;import java.util.List;public class RoomWriteActivity extends AppCompatActivity implements View.OnClickListener {private EditText et_name;private EditText et_author;private EditText et_press;private EditText et_price;private BookInfoDao bookInfoDao;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_room_write);et_name = findViewById(R.id.et_name);et_author = findViewById(R.id.et_author);et_press = findViewById(R.id.et_press);et_price = findViewById(R.id.et_price);findViewById(R.id.btn_save).setOnClickListener(this);findViewById(R.id.btn_delete).setOnClickListener(this);findViewById(R.id.btn_update).setOnClickListener(this);findViewById(R.id.btn_query).setOnClickListener(this);//从App实例中获取唯一的书籍持久化对象bookInfoDao = MyApplication.getInstance().getBookDB().bookInfoDao();}@Overridepublic void onClick(View v) {String name = et_name.getText().toString();String author = et_author.getText().toString();String press = et_press.getText().toString();String price = et_price.getText().toString();if (v.getId() == R.id.btn_save){BookInfo bookInfo = new BookInfo(null, name, author, press, Double.valueOf(price));bookInfoDao.insert(bookInfo);ToastUtlis.show(this,"保存成功");}else if (v.getId() == R.id.btn_query){List<BookInfo> list = bookInfoDao.queryAll();list.forEach(b-> Log.d("ning",b.toString()));ToastUtlis.show(this,"查询成功");}else if (v.getId()==R.id.btn_delete){BookInfo bookInfo = new BookInfo();bookInfo.setId(1);bookInfoDao.delete(bookInfo);ToastUtlis.show(this,"删除成功");}else {BookInfo bookInfo = bookInfoDao.queryByName(name);bookInfo.setAuthor(author);bookInfo.setPress(press);bookInfo.setPrice(Double.valueOf(price));bookInfoDao.update(bookInfo);ToastUtlis.show(this,"修改成功");}}
}
8.页面xml layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:padding="5dp"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="40dp"android:orientation="horizontal"><TextViewandroid:id="@+id/tv_name"android:layout_width="wrap_content"android:layout_height="match_parent"android:gravity="center"android:text=" 书名:"android:textColor="@color/black"android:textSize="17sp" /><EditTextandroid:id="@+id/et_name"android:layout_width="0dp"android:layout_height="match_parent"android:layout_marginTop="3dp"android:layout_marginBottom="3dp"android:layout_weight="1"android:background="@drawable/edit_select"android:hint="请输入书籍名称"android:inputType="text"android:textColor="@color/black"android:textSize="17sp" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="40dp"android:orientation="horizontal"><TextViewandroid:id="@+id/tv_author"android:layout_width="wrap_content"android:layout_height="match_parent"android:gravity="center"android:text=" 作者:"android:textColor="@color/black"android:textSize="17sp" /><EditTextandroid:id="@+id/et_author"android:layout_width="0dp"android:layout_height="match_parent"android:layout_marginTop="3dp"android:layout_marginBottom="3dp"android:layout_weight="1"android:background="@drawable/edit_select"android:hint="请输入作者姓名"android:textColor="@color/black"android:textSize="17sp" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="40dp"android:orientation="horizontal"><TextViewandroid:id="@+id/tv_press"android:layout_width="wrap_content"android:layout_height="match_parent"android:gravity="center"android:text="出版社:"android:textColor="@color/black"android:textSize="17sp" /><EditTextandroid:id="@+id/et_press"android:layout_width="0dp"android:layout_height="match_parent"android:layout_marginTop="3dp"android:layout_marginBottom="3dp"android:layout_weight="1"android:background="@drawable/edit_select"android:hint="请输入出版社名称"android:textColor="@color/black"android:textSize="17sp" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="40dp"android:orientation="horizontal"><TextViewandroid:id="@+id/tv_price"android:layout_width="wrap_content"android:layout_height="match_parent"android:gravity="center"android:text=" 价格:"android:textColor="@color/black"android:textSize="17sp" /><EditTextandroid:id="@+id/et_price"android:layout_width="0dp"android:layout_height="match_parent"android:layout_marginTop="3dp"android:layout_marginBottom="3dp"android:layout_weight="1"android:background="@drawable/edit_select"android:hint="请输入书籍价格"android:inputType="numberDecimal"android:textColor="@color/black"android:textSize="17sp" /></LinearLayout><Buttonandroid:id="@+id/btn_save"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="添加"android:textColor="@color/black"android:textSize="17sp" /><Buttonandroid:id="@+id/btn_delete"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="删除"android:textColor="@color/black"android:textSize="17sp" /><Buttonandroid:id="@+id/btn_update"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="修改"android:textColor="@color/black"android:textSize="17sp" /><Buttonandroid:id="@+id/btn_query"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="查询"android:textColor="@color/black"android:textSize="17sp" /></LinearLayout>
这篇关于Jetpack Room的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!