简体   繁体   English

插入数据库时​​出现java.lang.IllegalStateException

[英]java.lang.IllegalStateException when insert into database

I get java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase when insert into TABLE_STOCKUNIT .当插入TABLE_STOCKUNIT时,我得到java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase When you insert into TABLE_PRODUCT , there is no such problem.Tell me, please, why the problem arises, because db.close() is called after the db.insert() ?当你插入TABLE_PRODUCT ,没有这个问题。请告诉我,为什么会出现这个问题,因为db.close()是在db.insert()之后调用的?

 public long addProduct(ProductDescription product, int quantity) {
    long rows;
    SQLiteDatabase db=null;
        try {
            db = this.getWritableDatabase();
            ContentValues value = new ContentValues();
            value.put("producttype_id", 0);
            value.put("barCode", product.getId());
            value.put("name", product.getName());
            value.put("value", product.getPrice());
            value.put("measure_id", 0);
            value.put("precision", 0);
            rows = db.insert(TABLE_PRODUCT, null, value);


        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

        try {
            ContentValues value = new ContentValues();
            value.put("stock_id", 0);
            value.put("product_id", getProductByBarCode(product.getId()).getKey());
            value.put("qty", quantity);
            long row = db.insert(TABLE_STOCKUNIT, null, value); //java.lang.IllegalStateException


            db.close();

        } catch (Exception e) {
            e.printStackTrace();
            return -2;
        }


    return rows; // return rows inserted.
}

Synchronize ur first SQLiteDatabase db insertion like this,to make sure this invocation is given the top most priority by the main thread and every other operation by any other thread is halted(if any) until the insertion takes place:像这样同步你的第一个 SQLiteDatabase db 插入,以确保主线程给予此调用最高优先级,并且任何其他线程的所有其他操作都停止(如果有),直到插入发生:

synchronized(db) {
      try {
        db = this.getWritableDatabase();
        ContentValues value = new ContentValues();
        value.put("producttype_id", 0);
        value.put("barCode", product.getId());
        value.put("name", product.getName());
        value.put("value", product.getPrice());
        value.put("measure_id", 0);
        value.put("precision", 0);
        rows = db.insert(TABLE_PRODUCT, null, value);


    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM