Android : Room 数据库的基本用法 _简单应用_二_优化

2023-12-14 18:22:54

1.导入依赖 build.gradle

dependencies {
    //Room
    def room_version = "2.5.0"
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

    // 使用androidx版本库  ViewModelProviders
    implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0-alpha03'
}

2.PeopleDAtaBase.java 修改 为单例:

package com.example.myroom.dao;

import android.content.Context;

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

import com.example.myroom.entity.People;

/** 优化 改成单例模式 singleton
抽象类 继承 RoomDatabase      我们不用实现people中的方法
 version = 1 版本号,exportSchema = false不允许导出数据库的架构
 */
@Database(entities = {People.class}, version = 1, exportSchema = false)
public abstract class PeopleDataBase extends RoomDatabase {

    private static PeopleDataBase peopleDataBase;

    public static synchronized PeopleDataBase getPeopleDataBase(Context context){
        if(peopleDataBase == null){
            peopleDataBase = Room.databaseBuilder(context.getApplicationContext(),PeopleDataBase.class,"peopleDB")
// 默认不允许在主线程中连接数据库   在主线程中处理  使用了异步任务AsyncTask
//                    .allowMainThreadQueries()
                    .build();
        }
        return peopleDataBase;
    }

/**
* Java 抽象类的一些特点
* 不能被实例化:抽象类不能被实例化,因为它没有具体的实现细节。它只能被继承,并且子类必须实现抽象类中的所有抽象方法。
* 包含抽象方法:抽象类可以包含抽象方法,这些方法只有声明但没有实现。子类必须实现这些抽象方法,否则它也必须被声明为抽象类。
* 提供通用功能和行为:抽象类提供了一些通用功能和行为,这些功能和行为可以被其子类继承和重用。子类可以根据需要扩展这些功能和行为,或者重写它们以提供不同的实现。
* 用于设计高层次的抽象:抽象类可以用于表示一个高层次的抽象概念或者一个通用模板,使得代码更加模块化和可维护。通过将一些公共方法和行为提取到一个抽象类中,可以避免在多个子类中重复实现相同的功能。
* 扩展性:抽象类可以定义一些扩展的接口,子类可以选择实现这些接口来提供额外的功能。这使得抽象类具有很好的扩展性,可以根据需要添加新的功能和行为
*/
    public abstract  PeopleDao peopleDao();




}

3.添加异步任务 AsyncTask

3.1保存数据方法:InsertAsyncTask .java

package com.example.myroom.task;

import android.os.AsyncTask;

import com.example.myroom.dao.PeopleDao;
import com.example.myroom.entity.People;
/** AsyncTask 在 API 级别 30 中此字段已弃用 , 请改用标准或 Kotlin 并发实用程序
 * 插入数据 异步任务
 *	android.os.AsyncTask<Params、进度、结果>
 * */
public class InsertAsyncTask extends AsyncTask<People,Void,Void> {

    /**
     * 4个步骤
     * 执行异步任务时,任务会经历 4 个步骤:
     *
     * onPreExecute(),在任务之前的 UI 线程上调用 被执行。此步骤通常用于设置任务,例如 在用户界面中显示进度条。
     *
     * doInBackground(Params),在后台线程上调用 执行完毕后立即执行。
     * 此步骤用于 执行可能需要很长时间的后台计算。参数 的异步任务被传递到此步骤。
     * 计算结果必须 由此步骤返回,并将传递回最后一步。这一步 还可用于发布一个或多个单元 的进步。
     * 这些值在步骤中发布在 UI 线程上。onPreExecute()publishProgress(Progress)onProgressUpdate(Progress)
     *
     * onProgressUpdate(Progress),在 UI 线程上调用 调用 。
     * 执行的时间是 定义。此方法用于在用户中显示任何形式的进度 接口,而后台计算仍在执行。
     * 例如 它可用于对进度条进行动画处理或在文本字段中显示日志。publishProgress(Progress)
     *
     * onPostExecute(Result),在后台之后的 UI 线程上调用 计算完成。将后台计算的结果传递给主界面。
     * */
    private PeopleDao peopleDao;
    public InsertAsyncTask(PeopleDao peopleDao){
        this.peopleDao=peopleDao;
    }

    @Override
    protected Void doInBackground(People... people) {
        //在后台执行 插入数据操作
        peopleDao.insertDataS(people);
        return null;
    }
}

3.2删除数据方法:DeleteAsyncTask?.java

package com.example.myroom.task;

import android.os.AsyncTask;

import com.example.myroom.dao.PeopleDao;
import com.example.myroom.entity.People;

public class DeleteAsyncTask extends AsyncTask<People,Void,Void> {
    private PeopleDao peopleDao;
    public DeleteAsyncTask(PeopleDao peopleDao){
        this.peopleDao = peopleDao;
    }
    @Override
    protected Void doInBackground(People... people) {
        peopleDao.deleteDataS(people);
        return null;
    }
}

3.3 删除表数据方法?DeleteTBAsyncTask .java

package com.example.myroom.task;

import android.os.AsyncTask;

import com.example.myroom.dao.PeopleDao;

public class DeleteTBAsyncTask extends AsyncTask<Void,Void,Void> {
    private PeopleDao peopleDao;

    public DeleteTBAsyncTask(PeopleDao peopleDao) {
        this.peopleDao = peopleDao;
    }

    @Override
    protected Void doInBackground(Void... voids) {
        peopleDao.deleteTableData();
        return null;
    }
}

3.4 根据id查询数据方法?SelectByIdAsyncTask .java

package com.example.myroom.task;

import android.os.AsyncTask;

import com.example.myroom.dao.PeopleDao;
import com.example.myroom.entity.People;

public class SelectByIdAsyncTask extends AsyncTask<Integer,Void,People> {
    private PeopleDao peopleDao;

    public SelectByIdAsyncTask(PeopleDao peopleDao) {
        this.peopleDao = peopleDao;
    }

    @Override
    protected People doInBackground(Integer... integers) {
        People people =peopleDao.getPeople(integers[0]);
        return people;
    }
}

3.5 更新数据方法?UpdateAsyncTask .java

package com.example.myroom.task;

import android.os.AsyncTask;

import com.example.myroom.dao.PeopleDao;
import com.example.myroom.entity.People;

public class UpdateAsyncTask extends AsyncTask<People,Void,Void> {
    private PeopleDao peopleDao;
    public UpdateAsyncTask( PeopleDao peopleDao){
        this.peopleDao = peopleDao;
    }

    @Override
    protected Void doInBackground(People... people) {
        peopleDao.updateData(people);
        return null;
    }
}

4.修改PeopleDao.java

@Dao
public interface PeopleDao {
        ...

    //查询 根据id倒序
    @Query("select * from people order by id desc")
    LiveData<List<People>> getPeopleLive(); //设置成为可以观察的数据 LiveDAta
    //    List<People> getPeoples();

    ...
}

5.创建仓库 PeopleRepository.java

package com.example.myroom.dao;

import android.content.Context;
import android.util.Log;

import androidx.lifecycle.LiveData;

import com.example.myroom.entity.People;
import com.example.myroom.task.DeleteAsyncTask;
import com.example.myroom.task.DeleteTBAsyncTask;
import com.example.myroom.task.InsertAsyncTask;
import com.example.myroom.task.SelectByIdAsyncTask;
import com.example.myroom.task.UpdateAsyncTask;

import java.util.List;

public class PeopleRepository {
    PeopleDao peopleDao;
    LiveData<List<People>> allPeopleLive;

    public PeopleRepository(Context context) {
        PeopleDataBase peopleDataBase = PeopleDataBase.getPeopleDataBase(context.getApplicationContext());
        peopleDao = peopleDataBase.peopleDao();
        allPeopleLive = peopleDao.getPeopleLive();
    }

    public LiveData<List<People>> getAllPeopleLive() {
        return allPeopleLive;
    }

    public void insertPeoples(People... people) {
        new InsertAsyncTask(peopleDao).execute(people);
    }

    public void updatePeoples(People... people) {
        new UpdateAsyncTask(peopleDao).execute(people);
    }

    public void deletePeople(People... people) {
        new DeleteAsyncTask(peopleDao).execute(people);
    }

    public void deleteTBPeoples() {
        new DeleteTBAsyncTask(peopleDao).execute();
    }

    public People selectPeopleById(Integer id) {
        People people = null;
        try {
            people = new SelectByIdAsyncTask(peopleDao).execute(id).get();
        } catch (Exception e) {
            Log.e("TAG", "根据id查询失败" + e.getMessage());

        }
        return people;
    }

}

6.创建MyViewModel .java??

package com.example.myroom;

import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.example.myroom.dao.PeopleDao;
import com.example.myroom.dao.PeopleRepository;
import com.example.myroom.entity.People;

import java.util.List;

//管理界面数据
public class MyViewModel extends AndroidViewModel {
   private PeopleDao peopleDao;
   private PeopleRepository peopleRepository;

    public MyViewModel(@NonNull Application application) {
        super(application);
        peopleRepository = new PeopleRepository(application);
    }

    public LiveData<List<People>> getAllPeopleLive() {
        return peopleRepository.getAllPeopleLive();
    }
    public void insertPeoples(People... people){
        peopleRepository.insertPeoples(people);
    }

    public void updatePeoples(People... people){
        peopleRepository.updatePeoples(people);
    }

    public void deletePeople(People... people){
        peopleRepository.deletePeople(people);
//        new DeleteAsyncTask(peopleDao).execute(people);
    }

    public void deleteTBPeoples(){
        peopleRepository.deleteTBPeoples();

    }
    public People selectPeopleById(Integer id){
        return peopleRepository.selectPeopleById(id);
    }



}

7.MainActivity.java

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.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.myroom.dao.PeopleDao;
import com.example.myroom.dao.PeopleDataBase;
import com.example.myroom.entity.People;
import com.example.myroom.task.DeleteTBAsyncTask;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    PeopleDataBase DB;
    PeopleDao peopleDao;
    MyViewModel myViewModel;
    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);
//        binding = DataBindingUtil.setContentView(this,R.layout.activity_main);


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

        myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);

        DB = PeopleDataBase.getPeopleDataBase(this);
        peopleDao = DB.peopleDao();
        //观察数据
        myViewModel.getAllPeopleLive().observe(this, new Observer<List<People>>() {
            @Override
            public void onChanged(List<People> peoples) {
                //内容发生改变执行执行下面代码
                StringBuilder text = new StringBuilder();
                for (int i = 0; i < peoples.size(); i++) {
                    People people = peoples.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");
                }
                textContent.setText(text.toString());

            }
        });
//        //查询数据
//        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);
                myViewModel.insertPeoples(people);

//                new InsertAsyncTask(peopleDao).execute(people);

//                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);
                    myViewModel.updatePeoples(people);

//                    new UpdateAsyncTask(peopleDao).execute(people);
//                    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);
                    myViewModel.deletePeople(people);

//                    new DeleteAsyncTask(peopleDao).execute(people);
//                    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) {
                    selectDataById(id);
                }

            }
        });

        //删除全部数据
        btnDeleteData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                DB.peopleDao().deleteTableData();
                new DeleteTBAsyncTask(peopleDao).execute();
            }
        });

    }

    /**
     * 查询数据的方法
     */
    public void selectDataById(Integer id) {
        try {
            StringBuilder text = new StringBuilder();
//                People people = DB.peopleDao().getPeople(id);
//            People people = new SelectByIdAsyncTask(peopleDao).execute(id).get();

            People people = myViewModel.selectPeopleById(id);
            text.append("id:")
                    .append(people.getId())
                    .append("---name:")
                    .append(people.getName())
                    .append("---age:")
                    .append(people.getAge())
                    .append("---sex:");
            textContent.setText(text.toString());

        } catch (Exception e) {
            Log.e("TAG", "----查询失败------------" + e.getMessage());
        }


    }

}

文章来源:https://blog.csdn.net/jiayou2020527/article/details/134926749
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。