摘要
SQLiteDatabase.insertOrThrow()执行,不抛出异常,并返回正整数;但是,记录不会写入数据库。
详情
我正在实现存储库模式,并拥有一个通用的基础存储库。
public class BaseRepository<T> implements Repository<T> {
private enum Operation {
Add, Update, Delete
}
private final SQLiteOpenHelper openHelper;
private final String tableName;
private final Mapper<T, ContentValues> toContentValues;
private final Mapper<Cursor, T> toTypeMapper;
public BaseRepository(Context context, String tableName, Mapper<T, ContentValues> toContentValues,
Mapper<Cursor, T> toTypeMapper) {
this.openHelper = new DbOpenHelper(context);
this.tableName = tableName;
this.toContentValues = toContentValues;
this.toTypeMapper = toTypeMapper;
}
@Override
public void add(T item) {
transaction(Operation.Add, item, null);
}
@Override
public void update(T item, String filter) {
transaction(Operation.Update, item, filter);
}
@Override
public void delete(String filter) {
transaction(Operation.Delete, null, filter);
}
private void transaction(Operation operation, T item, String filter) {
final SQLiteDatabase database = openHelper.getWritableDatabase();
database.beginTransaction();
try {
switch (operation) {
case Add:
try { // For debugging, to catch any possible exception
ContentValues values = toContentValues.map(item);
long result = database.insertOrThrow(tableName, null, values);
String temp = ""; // For debugging
} catch (Exception e) {
String message = e.getMessage(); // For debugging
}
break;
case Update:
database.update(tableName, toContentValues.map(item), filter, null);
break;
case Delete:
database.delete(tableName, filter, null);
break;
}
} finally {
database.endTransaction();
database.close();
}
}
}
它进入transaction()
方法,并运行database.insert()
方法。我设置了断点并检查了表名和值。表名正确且值正确。该方法运行并返回一个正整数,表示插入成功。但是,当我检查数据库时,未插入记录。
我有获取数据的方法,但它们正常运行。如果我手动添加行,get
方法可以成功运行。
关于这里发生了什么的任何想法?我已经被困在这几个小时了。
谢谢!
答案 0 :(得分:0)
想出来。我忘记了database.setTransactionSuccessful()
:
private void transaction(Operation operation, T item, String filter) {
final SQLiteDatabase database = openHelper.getWritableDatabase();
database.beginTransaction();
try {
switch (operation) {
case Add:
try { // For debugging, to catch any possible exception
ContentValues values = toContentValues.map(item);
long result = database.insertOrThrow(tableName, null, values);
String temp = ""; // For debugging
} catch (Exception e) {
String message = e.getMessage(); // For debugging
}
break;
case Update:
database.update(tableName, toContentValues.map(item), filter, null);
break;
case Delete:
database.delete(tableName, filter, null);
break;
}
database.setTransactionSuccessful(); // Added this.
} finally {
database.endTransaction();
database.close();
}
}