问题场景:
在app首次启动使用到db的时候,后台提示如下错误信息
java.lang.IllegalStateException: getDatabase called recursively at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:204) at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
问题产生的原因分析
app的db想关的操作SQLiteOpenHelper的实现类中,app在publicvoid onCreate(SQLiteDatabase db)或者是publicvoid onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)中在其他线程或者是在这些方法体有其他的db模块调用到了getWritableDatabase进行db的新增,修改,删除等操作就会导致此问题
?解决方案:
如果在onCreate或者是onUpdate的过程中有调用到其他模块进行相同db操作,则需要进行类似于下面内容的处理:
private SQLiteDatabase mDefaultWritableDatabase = null; @Override public SQLiteDatabase getWritableDatabase() { final SQLiteDatabase db; if(mDefaultWritableDatabase != null){ db = mDefaultWritableDatabase; } else { db = super.getWritableDatabase(); } return db; } @Override public void onCreate(SQLiteDatabase db) { this.mDefaultWritableDatabase = db; } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { this.mDefaultWritableDatabase = db; } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { this.mDefaultWritableDatabase = db; }
?