【发布时间】:2016-03-03 04:55:38
【问题描述】:
我在 Android 上使用 com.j256.ormlite:ormlite-android:4.48。
我使用带有单例模式的 OrmLiteSqliteOpenHelper(整个应用程序只有一个实例)。
我编写了一个测试应用程序(使用多个 AsyncTask 和 read/create/update 操作),它工作正常,甚至在发布模式下测试它。
它在我的手机(Samsung S3 和 Mi4i)上运行的实际生产/发布中运行良好,但偶尔我会收到来自其他用户的带有 SQLiteDatabaseLockedException 的错误报告。
我想知道是我做错了什么,还是 SQLite 在不同的安卓手机上有不同的不可预知的行为?
以下是我的一些代码:
public class DbHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "test.db";
private static final int DATABASE_VERSION = 1;
private Dao<ModelA, String> modelADao = null;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
// this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, ModelA.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
}
public Dao<ModelA, String> getModelADao() throws SQLException {
if (modelADao == null) {
modelADao = getDao(ModelA.class);
}
return modelADao;
}
}
@DatabaseTable(tableName = "model_a")
public class ModelA {
@DatabaseField(id = true, columnName = "_id")
public String id;
@DatabaseField(columnName = "created")
public Date created;
@DatabaseField(columnName = "name")
public String name;
@DatabaseField(columnName = "age")
public int age;
@DatabaseField(columnName = "is_active")
public boolean isActive;
}
public class App {
public static final String TAG = App.class.getName();
private static DbHelper dbHelper;
public synchronized static DbHelper buildDbHelper(Context context) {
if (dbHelper == null) {
Log.d(TAG, "buildDbHelper");
dbHelper = OpenHelperManager.getHelper(context, DbHelper.class);
}
return dbHelper;
}
public static DbHelper getDbHelper() {
if (dbHelper == null) {
Log.e(TAG, "getDbHelper=null");
}
return dbHelper;
}
}
# Read
List<ModelA> items = App.getDbHelper().getModelADao().queryForAll();
# Create
Dao<ModelA, String> dao = App.getDbHelper().getModelADao();
ModelA item = new ModelA();
item.id = UUID.randomUUID().toString();
item.name = item.id;
item.created = Calendar.getInstance().getTime();
item.age = rand.nextInt(100);
dao.create(item);
【问题讨论】: