如何将数据保存到房间?

时间:2019-06-03 08:18:47

标签: java android

根据文档Android

我创建了这个

数据库:AppDatabase.java

package com.tsurumaru.dzil.clientwarehouse.persistence.db;

import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;

import com.tsurumaru.dzil.clientwarehouse.persistence.db.dao.QueueIncomingDao;
import com.tsurumaru.dzil.clientwarehouse.persistence.db.entity.QueueIncomingEntity;

import java.text.SimpleDateFormat;
import java.util.Date;

@Database(entities = {QueueIncomingEntity.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase instance;

    public abstract QueueIncomingDao queueIncomingDao();

    public static synchronized AppDatabase getInstance(Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(context.getApplicationContext(),
                    AppDatabase.class, "app_database")
                    .fallbackToDestructiveMigration()
                    .addCallback(roomCallback)
                    .build();
        }
        return instance;
    }

    private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);

            /**
             * For Testing database
             * */

            new PopulateDbAsyncTask(instance).execute();

        }
    };

    private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {

        private QueueIncomingDao queueIncomingDao;

        private PopulateDbAsyncTask(AppDatabase db) {
            queueIncomingDao = db.queueIncomingDao();
        }

        @Override
        protected Void doInBackground(Void... voids) {

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = formatter.format(new Date());

            for (int i = 0; i < 10; i++) {
                queueIncomingDao.insert(
                        new QueueIncomingEntity(
                                "Dzil " + (i + 1),
                                "B 3895 UKM",
                                formattedDate,
                                "EXAMPLE",
                                "OK", "Waiting"
                        )
                );
            }

            return null;
        }
    }

}

实体:QueueIncomingEntity.java

package com.tsurumaru.dzil.clientwarehouse.persistence.db.entity;

import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;

@Entity(tableName = "queue_incoming")
public class QueueIncomingEntity {

    @PrimaryKey(autoGenerate = true)
    private Integer id;

    @ColumnInfo(name = "driver")
    private String driver;

    @ColumnInfo(name = "vehicle_number")
    private String vehicleNumber;

    @ColumnInfo(name = "date_unique_number")
    private String dateUniqueNumber;

    @ColumnInfo(name = "unique_number")
    private String uniqueNumber;

    @ColumnInfo(name = "message")
    private String message;

    @ColumnInfo(name = "status")
    private String status;

    public Integer getId() {
        return id;
    }

    public String getDriver() {
        return driver;
    }

    public String getVehicleNumber() {
        return vehicleNumber;
    }

    public String getDateUniqueNumber() {
        return dateUniqueNumber;
    }

    public String getUniqueNumber() {
        return uniqueNumber;
    }

    public String getMessage() {
        return message;
    }

    public String getStatus() {
        return status;
    }

    public QueueIncomingEntity(String driver, String vehicleNumber, String dateUniqueNumber, String uniqueNumber, String message, String status) {
        this.driver = driver;
        this.vehicleNumber = vehicleNumber;
        this.dateUniqueNumber = dateUniqueNumber;
        this.uniqueNumber = uniqueNumber;
        this.message = message;
        this.status = status;
    }

    // Rencananya, ID akan didapatkan dari hasil scan
    public void setId(Integer id) {
        this.id = id;
    }
}

DAO:QueueIncomingDao.java

package com.tsurumaru.dzil.clientwarehouse.persistence.db.dao;

import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;

import java.util.List;
import com.tsurumaru.dzil.clientwarehouse.persistence.db.entity.QueueIncomingEntity;

@Dao
public interface QueueIncomingDao {

    @Insert
    void insert(QueueIncomingEntity queueIncomingEntity);

    @Update
    void update(QueueIncomingEntity queueIncomingEntity);

    @Delete
    void delete(QueueIncomingEntity queueIncomingEntity);

    @Query("DELETE FROM queue_incoming")
    void deleteAll();

    @Query("SELECT * FROM queue_incoming ORDER BY id DESC")
    LiveData<List<QueueIncomingEntity>> getAll();

}

存储库:QueueIncomingRepository.java

package com.tsurumaru.dzil.clientwarehouse.persistence.db.repository;

import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.os.AsyncTask;

import com.tsurumaru.dzil.clientwarehouse.persistence.db.AppDatabase;
import com.tsurumaru.dzil.clientwarehouse.persistence.db.dao.QueueIncomingDao;
import com.tsurumaru.dzil.clientwarehouse.persistence.db.entity.QueueIncomingEntity;

import java.util.List;

public class QueueIncomingRepository {
    private QueueIncomingDao queueIncomingDao;
    private LiveData<List<QueueIncomingEntity>> listLiveData;


    public QueueIncomingRepository(Application application) {

        AppDatabase database = AppDatabase.getInstance(application);
        queueIncomingDao = database.queueIncomingDao();

        // Get all data, like actionIndex in Yii2
        listLiveData = queueIncomingDao.getAll();
    }


    /*
     * Room not allowed in main thread
     * Using AsyncTask
     * */
    public void insert(QueueIncomingEntity queueIncomingEntity) {
        new InsertAsyncTask(queueIncomingDao).execute(queueIncomingEntity);
    }

    public void update(QueueIncomingEntity queueIncomingEntity) {
        new UpdateAsyncTask(queueIncomingDao).execute(queueIncomingEntity);
    }

    public void delete(QueueIncomingEntity queueIncomingEntity) {
        new DeleteAsyncTask(queueIncomingDao).execute(queueIncomingEntity);
    }

    public void deleteAll() {
        new DeleteAllAsyncTask(queueIncomingDao).execute();
    }

    public LiveData<List<QueueIncomingEntity>> getAll() {
        return listLiveData;
    }

    /** =========================================================== **/
    /**
     *Doing in AsyncTask
     */

    private static class InsertAsyncTask extends AsyncTask<QueueIncomingEntity, Void, Void> {

        private QueueIncomingDao queueIncomingDao;

        private InsertAsyncTask(QueueIncomingDao queueIncomingDao) {
            this.queueIncomingDao = queueIncomingDao;
        }

        @Override
        protected Void doInBackground(QueueIncomingEntity... queueIncomingEntities) {
            queueIncomingDao.insert(queueIncomingEntities[0]);
            return null;
        }
    }

    private static class UpdateAsyncTask extends AsyncTask<QueueIncomingEntity, Void, Void> {

        private QueueIncomingDao queueIncomingDao;

        private UpdateAsyncTask(QueueIncomingDao queueIncomingDao) {
            this.queueIncomingDao = queueIncomingDao;
        }

        @Override
        protected Void doInBackground(QueueIncomingEntity... queueIncomingEntities) {
            queueIncomingDao.update(queueIncomingEntities[0]);
            return null;
        }
    }

    private static class DeleteAsyncTask extends AsyncTask<QueueIncomingEntity, Void, Void> {

        private QueueIncomingDao queueIncomingDao;

        private DeleteAsyncTask(QueueIncomingDao queueIncomingDao) {
            this.queueIncomingDao = queueIncomingDao;
        }

        @Override
        protected Void doInBackground(QueueIncomingEntity... queueIncomingEntities) {
            queueIncomingDao.delete(queueIncomingEntities[0]);
            return null;
        }
    }

    private static class DeleteAllAsyncTask extends AsyncTask<Void, Void, Void> {

        private QueueIncomingDao queueIncomingDao;

        private DeleteAllAsyncTask(QueueIncomingDao queueIncomingDao) {
            this.queueIncomingDao = queueIncomingDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            queueIncomingDao.deleteAll();
            return null;
        }
    }

}

我是新来的房间。 如何在实体“ queue_incoming”中声明时插入表中?

现在,我有一个实体可以像这样插入:

public class PostAntamIncomingScanQR extends AsyncTask<Void, Void, Boolean> {
    //Class Constructor
    public PostAntamIncomingScanQR(
            Context context,
            String driverName,
            String vehicleNumber,
            String dateUniqueNumber,
            String uniqueCode,
            ArrayList<BagLotNumberModel> bagLotNumbers
    ) {
        //Initializing variables
        this.context = context;
        this.bagLotNumbers = bagLotNumbers;
        this.vehicleNumber = vehicleNumber;
        this.driverName = driverName;
        this.uniqueCode = uniqueCode;
        this.dateUniqueNumber = dateUniqueNumber;
    }

    @Override
    protected Boolean doInBackground(Void... params) {

        // Save to internal database
        QueueIncomingEntity queueIncomingEntity = new QueueIncomingEntity(
                driverName,
                vehicleNumber,
                dateUniqueNumber,
                uniqueCode,
                null,
                "Waiting"
        );

        // how to insert them

    }

}

任何对此表示赞赏的建议

2 个答案:

答案 0 :(得分:2)

要插入queueIncomingEntity,请获取数据库实例和Dao访问权限

主线程

AppDatabase.getInstance(context).queueIncomingDao().insert(queueIncomingEntity)

背景线程

QueueIncomingRepository(context).insert(queueIncomingEntity)

制定冲突策略更好

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(QueueIncomingEntity queueIncomingEntity)

答案 1 :(得分:1)

您可以使用您的仓库QueueIncomingRepository

插入
queueIncomingRepository.insert(queueIncomingEntity)

这样您的数据库查询将在后台线程中运行