插入java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase
时我得到TABLE_STOCKUNIT
。当您插入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.
}
答案 0 :(得分:0)
首先同步你的第一个SQLiteDatabase数据库插件,以确保主线程给予此调用最高优先级,并且任何其他线程的每个其他操作都将暂停(如果有),直到插入发生:
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;
}
}