【问题标题】:Room and rxjava database are not working?Room 和 rxjava 数据库不工作?
【发布时间】:2018-09-15 11:58:11
【问题描述】:

我想将 ROOM 与 Rxjava 一起使用,这些是我的代码:

我的数据库结构类:

    @Entity(tableName = "productSample1")
public class ProductEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private String name;
    private String price;

    public ProductEntity(int id, String name, String price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    @Ignore
    public ProductEntity(String name, String price) {
        this.name = name;
        this.price = price;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPrice() {
        return price;
    }

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

这是我的 ProductDAO 类:

@Dao
public interface ProductDAO {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(ProductEntity productEntity);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertAll(List<ProductEntity> products);

    @Delete
    void delete(ProductEntity productEntity);

    @Query("SELECT * FROM productSample1 where id=:id")
    ProductEntity getProductById(int id);

    @Query("Select * from productSample1 order by id desc")
    LiveData<List<ProductEntity>>getAll();

    @Query("Select * from productSample1 order by id desc")
    Single<List<ProductEntity>> getAllRXjava();

    @Query("delete from productSample1")
    int deleteAll();

    @Query("select count(*) from productSample1")
    int getCount();

}

这是我用于创建和管理数据库的数据库类:

    @Database(entities = {ProductEntity.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public static final String DATABASE_NAME="AppDatabase";
    private static volatile AppDatabase instance;
    private static final Object Lock=new Object();

    public abstract ProductDAO productDAO();

    public static AppDatabase getInstance(Context context){
        if(instance==null){
            synchronized (Lock){
                if(instance==null){
                    instance= Room.databaseBuilder(context.getApplicationContext(),
                        AppDatabase.class,DATABASE_NAME).build();
                }
            }
        }
        return instance;
    }
}

这是我处理数据库的活动:

   private AppDatabase mDb;
    private ProductDAO mDao;

mDb= AppDatabase.getInstance(this);
        mDao=mDb.productDAO();
        Log.v("this","dbCreated");

        ///////////one product
        ProductEntity product1=new ProductEntity(1,"prod1","2500");
        Completable.fromAction(() ->mDao.insert(product1))
                .subscribeOn(Schedulers.io())
                .subscribe(new CompletableObserver() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.v("this","error0 "+ e.getMessage() );
                    }
                });

        /////List of Products
        List<ProductEntity>productList=new ArrayList<>();
        productList.add(new ProductEntity("prod2","3500"));
        productList.add(new ProductEntity("prod3","4500"));
        productList.add(new ProductEntity("prod4","5500"));
        Completable.fromAction(() ->mDao.insertAll(productList))
                .subscribeOn(Schedulers.io())
                .subscribe(new CompletableObserver() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.v("this","error1 "+ e.getMessage() );
                    }
                });

        //getList of products
        mDao.getAllRXjava()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<List<ProductEntity>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(List<ProductEntity> productEntities) {
                        for (int i=0;i<productEntities.size();i++){
                            Log.v("this",productEntities.get(i).getName());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.v("this","error "+ e.getMessage() );
                    }
                });
    }

这是发生了什么,当我第一次启动我的活动类时,没有发生错误,当我从模拟器下载创建的数据库并在 sqlite 数据库管理器中打开它时,问题是文件为空并且没有创建数据库

当我返回并重新打开数据库时,我收到很多错误:

Cannot run invalidation tracker. Is the db closed?
    java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.
        at android.database.sqlite.SQLiteConnectionPool.throwIfClosedLocked(SQLiteConnectionPool.java:962)
        at android.database.sqlite.SQLiteConnectionPool.waitForConnection(SQLiteConnectionPool.java:599)
        at android.database.sqlite.SQLiteConnectionPool.acquireConnection(SQLiteConnectionPool.java:348)
        at android.database.sqlite.SQLiteSession.acquireConnection(SQLiteSession.java:894)
        at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:752)
        at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
        at android.arch.persistence.db.framework.FrameworkSQLiteStatement.executeUpdateDelete(FrameworkSQLiteStatement.java:45)
        at android.arch.persistence.room.InvalidationTracker$1.run(InvalidationTracker.java:321)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)

你能帮帮我吗?我的代码有什么问题?

【问题讨论】:

    标签: android rx-java2 android-room android-architecture-components


    【解决方案1】:

    之前我也有同样的问题。 Room 的数据库文件不显示任何数据。 它有数据,因为我能够记录它,但是一旦我从 android studio 中提取它,你就无法在 sql 浏览器中打开它。

    您应该尝试在某处记录数据并检查它是否工作正常。 就我而言,它工作正常,所以我继续前进。

    【讨论】:

    • 感谢回复,但有个问题,当我返回并重新打开活动时,我该怎么办?
    • 我认为您没有正确打开和关闭数据库。请参考活动发布一些开闭代码。
    猜你喜欢
    • 2019-04-20
    • 2020-10-29
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    相关资源
    最近更新 更多