所以在一些罕见的情况下,我看到“尝试编写只读数据库”的消息,我无法弄清问题所在。我将从我的logcat中的堆栈跟踪开始...正如您从时间戳中看到的那样,我在尝试写入之前仅检查了db.isReadOnly()1ms。 (isOpen = true,readOnly = false)
01-29 13:47:49.115: D/AWT(11055): #479.Got writable database (230537815): isOpen: (true) isReadOnly: (false) inTransaction: (false)
01-29 13:47:49.116: D/AWT(11055): #479.in transaction: Got writable database (230537815): isOpen: (true) isReadOnly: (false) inTransaction: (true)
01-29 13:47:49.116: E/SQLiteLog(11055): (1032) statement aborts at 15: [INSERT INTO Events(col1,col2,col3,col4) VALUES (?,?,?,?)]
01-29 13:47:49.117: E/SQLiteDatabase(11055): Error inserting data="scrubbed"
01-29 13:47:49.117: E/SQLiteDatabase(11055): android.database.sqlite.SQLiteReadOnlyDatabaseException: attempt to write a readonly database (code 1032)
01-29 13:47:49.117: E/SQLiteDatabase(11055): at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
01-29 13:47:49.117: E/SQLiteDatabase(11055): at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:780)
01-29 13:47:49.117: E/SQLiteDatabase(11055): at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
01-29 13:47:49.117: E/SQLiteDatabase(11055): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
01-29 13:47:49.117: E/SQLiteDatabase(11055): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
01-29 13:47:49.117: E/SQLiteDatabase(11055): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
01-29 13:47:49.117: E/SQLiteDatabase(11055): at com.company.DbHelper.insertBatch(EventsDbHelper.java:174)
01-29 13:47:49.117: D/AWT(11055): #479.finalizing transaction: Got writable database (230537815): isOpen: (true) isReadOnly: (false) inTransaction: (true)
01-29 13:47:49.118: W/SQLiteLog(12120): (28) file unlinked while open: /data/user/0/com.company.app/databases/MyDatabase.db
从我的来源:
public void insertBatch(LinkedList<WriteQueue.DatabaseRecord> writeQueue) throws Exception {
Log.d("AWT", "EventsDbHelper->insertBatch()");
if (writeQueue == null) {
return;
}
Iterator<DatabaseRecord> it = writeQueue.iterator();
SQLiteDatabase db = this.getWritableDatabase();
Log.d("AWT", String.format("Got writable database (%s): isOpen: (%s) isReadOnly: (%s) inTransaction: (%s)",
db.hashCode(), db.isOpen(), db.isReadOnly(), db.inTransaction()));
try {
db.beginTransaction();
while (it.hasNext()) {
DatabaseRecord record = it.next();
ContentValues initialValues = new ContentValues();
initialValues.put(col1, val1);
initialValues.put(col2, val2);
initialValues.put(col3, val3);
initialValues.put(col4, val4);
Log.d("AWT", String.format("in transaction: Got writable database (%s): isOpen: (%s) isReadOnly: (%s) inTransaction: (%s)",
db.hashCode(), db.isOpen(), db.isReadOnly(), db.inTransaction()));
db.insert(DBTBL, null, initialValues);
}
Log.d("AWT", String.format("finalizing transaction: Got writable database (%s): isOpen: (%s) isReadOnly: (%s) inTransaction: (%s)",
db.hashCode(), db.isOpen(), db.isReadOnly(), db.inTransaction()));
db.setTransactionSuccessful();
} catch (Exception e) {
Log.e(TAG, "Error inserting batch record into database.", e);
} finally {
try {
db.endTransaction();
db.close();
} catch (Exception e) {
Log.e(TAG, Global.DB_ERROR, e);
}
}
}
所以我认为可能发生了两件事之一。
此时出于想法,但我愿意尝试任何建议。
答案 0 :(得分:1)
因此,乍看之下,其根本原因似乎是第三方库。除非我弄错了,否则Mitix的Tagit会在app启动时删除数据库。我添加了一些详细的SQLite日志记录,包括这些策略:
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
我在日志中注意到在创建并打开数据库之后我的数据库被取消链接了。更详细的日志记录表明它在初始化Mobeix库时发生。有问题的违规行:
01-29 13:47:49.118: W/SQLiteLog(12120): (28) file unlinked while open: /data/user/0/com.company.app/databases/MyDatabase.db
所以我的数据库文件已取消链接。奇怪的。下一次调用getWritableDatabase()会再次重新创建它,然后它就可以了,直到应用程序被杀死并重新启动,此时它将被删除并重新创建。
如果我找出完全导致取消链接的原因,我会更新此内容。
答案 1 :(得分:1)
我或多或少地遇到了完全相同的问题,我发现了一个有意义的问题......
https://code.google.com/p/android/issues/detail?id=174566
我的解决方法 - 虽然不是最好的解决方案 - 是永远不会执行数据库修订并自行跟踪,因此从不调用onUpgrade()
,并在更新应用程序时手动执行升级。
或者,如果您有一个只读的小型数据库,则可以在onCreate()
类中的每个DBHelper
上触发资产中的数据库副本,但如果文件系统是只有这样才能找到更好的解决方案。
@Override
public void onCreate(SQLiteDatabase db) {
// Workaround for Issue 174566
myContext.deleteDatabase(DB_NAME);
try {
copyDataBase();
}
catch(IOException e) {
System.out.println("IOException " + e.getLocalizedMessage());
}
}
我的应用程序现在可以通过我的解决方法进行升级,并通过判断自从这个缺陷被提出以来有多长时间,它可能永远不会被修复...
对不起,这不是问题的完整解决方案,但它至少是一种前进的方式。
答案 2 :(得分:0)
我有类似的问题。但是,我故意删除当前数据库作为还原的一部分。
我认为发生的事情是SQLite将数据库标记为只读,以便提供针对file unlinked while open:
的保护。
恢复后,任何更新都将失败并显示attempt to write a readonly database (code 1032)
。
我的解决方案是重新实例化DBHelper。我通过添加reopen
方法来完成此操作。
e.g。
public static void reopen(Context context) {
instance = new DBHelper(context);
}
然后我使用
调用/调用它 if(copytaken && origdeleted && restoredone) {
DBHelper.reopen(context);
DBHelper.getHelper(context).expand(null,true);
}
对expand方法的调用是onUpgrade / versions的等效/ getaround。它根据与实际数据库进行比较的伪模式添加表和列。
完整的DBHelper是: -
/**
* DBHelper
*/
@SuppressWarnings("WeakerAccess")
class DBHelper extends SQLiteOpenHelper {
private static final String LOGTAG = "SW-DBHelper";
private static final String DBNAME = DBConstants.DATABASE_NAME;
private static final String dbcreated =
"001I Database " + DBNAME + " created.";
private static final String dbunusable =
"002E Database " + DBNAME +
" has been set as unusable (according to schema).";
private static final String dbexpanded =
"003I Database " + DBNAME + " expanded.";
private static final String dbexpandskipped =
"004I Database " + DBNAME + " expand skipped - nothing to alter.";
private static final String dbbuildskipped =
"005I Database" + DBNAME + " build skipped - no tables to add";
public static final String THISCLASS = DBHelper.class.getSimpleName();
/**
* Consrtuctor
*
* @param context activity context
* @param name database name
* @param factory cursorfactory
* @param version database version
*/
DBHelper(Context context, @SuppressWarnings("SameParameterValue") String name, @SuppressWarnings("SameParameterValue") SQLiteDatabase.CursorFactory factory, @SuppressWarnings("SameParameterValue") int version) {
super(context, name, factory, version);
}
/**
* Instantiates a new Db helper.
*
* @param context the context
*/
DBHelper(Context context) {
super(context, DBConstants.DATABASE_NAME, null, 1);
}
private static DBHelper instance;
/**
* Gets helper.
*
* @param context the context
* @return the helper
*/
static synchronized DBHelper getHelper(Context context) {
if(instance == null) {
instance = new DBHelper(context);
}
return instance;
}
@Override
public void onCreate(SQLiteDatabase db) {
expand(db, false);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
}
/**
* expand create database tables
*
* @param db SQLIte Database, if null then instance is used
* @param buildandexpand to attempt both create and expand
*/
void expand(SQLiteDatabase db, boolean buildandexpand) {
String mode = "Create Mode.";
if (buildandexpand) {
mode = "Expand Mode.";
}
String msg = mode;
String methodname = new Object(){}.getClass().getEnclosingMethod().getName();
LogMsg.LogMsg(LogMsg.LOGTYPE_INFORMATIONAL,LOGTAG,msg,THISCLASS,methodname);
// if no database has been passed then get the database
if(db == null) {
db = instance.getWritableDatabase();
}
// Build Tables to reflect schema (SHOPWISE) only if schema is usable
if(DBConstants.SHOPWISE.isDBDatabaseUsable()) {
// Check to see if any tables need to be added
ArrayList<String> buildsql = DBConstants.SHOPWISE.generateDBBuildSQL(db);
if (!buildsql.isEmpty()) {
DBConstants.SHOPWISE.actionDBBuildSQL(db);
msg = dbcreated + buildsql.size() + " tables added.";
LogMsg.LogMsg(LogMsg.LOGTYPE_INFORMATIONAL,LOGTAG,msg,THISCLASS,methodname);
} else {
msg = dbbuildskipped;
LogMsg.LogMsg(LogMsg.LOGTYPE_INFORMATIONAL,LOGTAG,msg,THISCLASS,methodname);
}
if(buildandexpand) {
ArrayList<String> altersql = DBConstants.SHOPWISE.generateDBAlterSQL(db);
if(!altersql.isEmpty()) {
msg = dbexpanded + altersql.size() + " columns added.";
LogMsg.LogMsg(LogMsg.LOGTYPE_INFORMATIONAL,LOGTAG,msg,THISCLASS,methodname);
DBConstants.SHOPWISE.actionDBAlterSQL(db);
} else {
msg = dbexpandskipped;
LogMsg.LogMsg(LogMsg.LOGTYPE_INFORMATIONAL,LOGTAG,msg,THISCLASS,methodname);
}
}
} else {
msg = dbunusable + "\n" +
DBConstants.SHOPWISE.getAllDBDatabaseProblemMsgs();
LogMsg.LogMsg(LogMsg.LOGTYPE_ERROR,LOGTAG,msg,THISCLASS,methodname);
}
}
public static void reopen(Context context) {
instance = new DBHelper(context);
}
}
答案 3 :(得分:0)
我遇到了类似的问题,实际上很烦人的是,它在任何时候都会发生,很难复制实现它的确切条件。我只关闭MainActivity类的ondestroy方法中的DDBB。我所做的是在每次使用db时添加一个try / catch并添加以下catch,在这种情况下它位于while循环的中间,在其他函数中我再次调用该函数一次:
catch (SQLException e) {
e.printStackTrace();
Log.d(TAG, "MainService: error in AccSaveToDB with "+mainDB.getPath()+" in iteration "+j+". Closing and re-opening DB");
DBHelper.close();
mainDB.close();
j--;
}
这是在访问数据库的每个函数的开头:
if (mainDB==null || !mainDB.isOpen()) {
DBHelper = DefSQLiteHelper.getInstance(getApplicationContext(), "Data.db", null, 1);
mainDB = DBHelper.getWritableDatabase();
}
到目前为止,我仍然有一段时间出现此错误,我还无法弄清楚原因,但至少我的应用程序没有崩溃,它恢复了它必须做的事情。我无法看到文件是否被删除,但这个解决方案对我有用
答案 4 :(得分:0)
我有同样的问题。我发现最简单的方法是在数据库对象上使用enableWriteAheadLogging()。
databaseObject.enableWriteAheadLogging()