简体   繁体   中英

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 . 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() ?

 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:

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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