mercredi 2 mars 2016

Android SQLiteDatabaseLockedException with ormlite

I am using com.j256.ormlite:ormlite-android:4.48 on Android.

I utilize OrmLiteSqliteOpenHelper with singleton pattern (only one instance for the entire app).

I wrote a testing app (using multiple AsyncTask with read/create/update operations) and it works fine, even test it in Release mode.

It works fine on actual production/release running on my phone (Samsung S3 and Mi4i), but occasionally I receive bug report with SQLiteDatabaseLockedException from other users.

I wonder did I do something wrong, or SQLite have different unpredictable behavior on different android phone?

Below are some of my code:

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

Aucun commentaire:

Enregistrer un commentaire