安卓room框架使用

该文章展示了如何在Android应用中使用Gradle导入依赖,创建Room数据持久化库的实体类、DAO接口和Database抽象类。通过编写`BookInfo`实体类,`BookDao`接口以及`BookDatabase`,实现了数据的插入、删除、更新和查询功能。此外,还涵盖了在`MyApplication`中初始化数据库并提供数据库实例的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.gradle中导入依赖

2.编写实体类

package com.example.chapter06.entity;

import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class BookInfo {
    //主键
    @PrimaryKey(autoGenerate=true)
    private int id;

    //姓名
    private String name;
    //作者
    private String author;
    //出版社
    private String press;
    //价格
    private double price;

    public BookInfo(int id, String name, String author, String press, double price) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.press = press;
        this.price = price;
    }

    @Override
    public String toString() {
        return "BookInfo{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", press='" + press + '\'' +
                ", price=" + price +
                '}';
    }

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

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

    public void setAuthor(String author) {
        this.author = author;
    }

    public void setPress(String press) {
        this.press = press;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getAuthor() {
        return author;
    }

    public String getPress() {
        return press;
    }

    public double getPrice() {
        return price;
    }
}

3.写Dao接口

package com.example.chapter06.dao;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;

import com.example.chapter06.entity.BookInfo;

import java.util.List;

@Dao
public interface BookDao {
    //插入
    @Insert
    void insert(BookInfo... book);
    //删除
    @Delete
    void delete(BookInfo... book);
    //删除所有
    @Delete
    void deleteAll();
    //更新
    @Update
    int 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.编写Database类 extends RoomDatabase

package com.example.chapter06.database;

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

import com.example.chapter06.dao.BookDao;
import com.example.chapter06.entity.BookInfo;

@Database(entities = {BookInfo.class},version = 1,exportSchema = true)
public abstract class BookDatabase extends RoomDatabase {
    public abstract BookDao bookDao();

}

5.编写myApplication extends Application

package com.example.chapter06;

import android.app.Application;
import android.content.res.Configuration;

import androidx.annotation.NonNull;
import androidx.room.Room;

import com.example.chapter06.dao.BookDao;
import com.example.chapter06.database.BookDatabase;

import java.util.HashMap;

public class MyApplication extends Application {
    private static MyApplication mApp;
    public  HashMap<String,String> infoMap=new HashMap<>();
    //声明数据库对象
    private  BookDatabase bookDatabase;
    public static MyApplication getInstance()
    {
      return mApp;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mApp=this;

        bookDatabase= Room.databaseBuilder(this,BookDatabase.class,"book")
                .addMigrations()
                //允许在主线程中操作数据库(Room默认不能在主线程中操作数据库
                .allowMainThreadQueries()
                .build();
    }

    @Override
    public void onTerminate()
    {
        super.onTerminate();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    //获取数据库实例
    public BookDatabase getBookDatabase()
    {
        return bookDatabase;
    }
}

6.写界面

<?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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">


            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="3"
                android:gravity="center"
                android:text="名称"
                android:textColor="@color/black"
                android:textSize="24sp" />

            <EditText
                android:id="@+id/et_name"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:ems="10"
                android:inputType="textPersonName" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">


            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="3"
                android:gravity="center"
                android:text="作者"
                android:textColor="@color/black"
                android:textSize="24sp" />

            <EditText
                android:id="@+id/et_author"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:ems="10"
                android:inputType="textPersonName" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">


            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="3"
                android:gravity="center"
                android:text="出版社"
                android:textColor="@color/black"
                android:textSize="24sp" />

            <EditText
                android:id="@+id/et_press"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:ems="10"
                android:inputType="textPersonName" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">


            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="3"
                android:gravity="center"
                android:text="价格"
                android:textColor="@color/black"
                android:textSize="24sp" />

            <EditText
                android:id="@+id/et_price"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="9"
                android:ems="10"
                android:inputType="textPersonName" />
        </LinearLayout>

        <CheckBox
            android:id="@+id/cb_Marry"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="是否已婚" />

        <Button
            android:id="@+id/btn_save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="添加" />

        <Button
            android:id="@+id/btn_delete"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="删除" />

        <Button
            android:id="@+id/btn_update"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="更新" />

        <Button
            android:id="@+id/btn_query"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="查询" />

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

7.写java逻辑处理代码

package com.example.chapter06;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.example.chapter06.dao.BookDao;
import com.example.chapter06.entity.BookInfo;
import com.example.chapter06.util.ToastUtil;

import java.util.List;

public class RoomWriteActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private EditText et_press;
    private EditText et_name;
    private EditText et_author;
    private EditText et_price;

    private CheckBox cb_marry;
    private Button btn_save;
    private Button btn_delete;
    private Button btn_update;
    private Button btn_query;
    private BookDao bookDao;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room_write);


        et_press = findViewById(R.id.et_press);
        et_name = findViewById(R.id.et_name);
        et_price = findViewById(R.id.et_price);
        et_author = findViewById(R.id.et_author);

        cb_marry = findViewById(R.id.cb_Marry);
        btn_save = findViewById(R.id.btn_save);
        btn_delete = findViewById(R.id.btn_delete);
        btn_update = findViewById(R.id.btn_update);
        btn_query = findViewById(R.id.btn_query);

        btn_delete.setOnClickListener(this);
        btn_query.setOnClickListener(this);
        btn_update.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        cb_marry.setOnCheckedChangeListener( this);

        bookDao = MyApplication.getInstance().getBookDatabase().bookDao();
        }

    @Override
    public void onClick(View view) {
        String press = et_press.getText().toString();
        String name = et_name.getText().toString();
        String author = et_author.getText().toString();
        String price = et_price.getText().toString();
        switch (view.getId())
        {
            case R.id.btn_save:
                BookInfo b=new BookInfo();
                b.setAuthor(author);
                b.setName(name);
                b.setPress(press);
                b.setPrice(Integer.parseInt(price));
                bookDao.insert(b);
                ToastUtil.show(this,"保存成功");
                break;
            case R.id.btn_query:
                List<BookInfo> list=bookDao.queryAll();
                for (BookInfo b1:list)
                {
                    Log.d("ning",b1.toString());
                }
                break;
            case R.id.btn_delete:
                BookInfo b2=new BookInfo();
                b2.setId(1);
                bookDao.delete(b2);
                break;
            case R.id.btn_update:
                BookInfo b4 = bookDao.queryByName(name);
                BookInfo b3 = new BookInfo();
                b3.setId(b4.getId());
                b3.setPrice(Integer.parseInt(price));
                b3.setPress(press);
                b3.setAuthor(author);
                b3.setName(name);
                bookDao.update(b3);
                break;

        }

    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值