寫了個小app,需要將資料存入sqlite中,按照文檔說明,如下方式建立資料庫檔案:
db_aimu = SQLiteDatabase.openOrCreateDatabase("test.db", null);
運行時logcat報錯:
02-22 09:16:28.214: E/SQLiteLog(26781): (14) cannot open file at line 30176 of [00bb9c9ce4]02-22 09:16:28.222: E/SQLiteLog(26781): (14) os_unix.c:30176: (2) open(//test.db) - 02-22 09:16:28.331: E/SQLiteDatabase(26781): Failed to open database 'test.db'.02-22 09:16:28.331: E/SQLiteDatabase(26781): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database02-22 09:16:28.331: E/SQLiteDatabase(26781): at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)02-22 09:16:28.331: E/SQLiteDatabase(26781): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)02-22 09:16:28.331: E/SQLiteDatabase(26781): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)02-22 09:16:28.331: E/SQLiteDatabase(26781): at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)02-22 09:16:28.331: E/SQLiteDatabase(26781): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)02-22 09:16:28.331: E/SQLiteDatabase(26781): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)02-22 09:16:28.331: E/SQLiteDatabase(26781): at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)02-22 09:16:28.331: E/SQLiteDatabase(26781): at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)02-22 09:16:28.331: E/SQLiteDatabase(26781): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)02-22 09:16:28.331: E/SQLiteDatabase(26781): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)02-22 09:16:28.331: E/SQLiteDatabase(26781): at com.test.test.<init>(test.java:21)02-22 09:16:28.331: E/SQLiteDatabase(26781): at com.test.test.getInstance(test.java:34)02-22 09:16:28.331: E/SQLiteDatabase(26781): at com.test.MainActivity$2.run(MainActivity.java:71)
似乎是開啟資料檔案失敗。
網上查閱資料,查看官方文檔,都沒有找到原因。最後有人提到:
I faced this problem, it was because in 4.2, there is multi users support, and if you are testing with non-admin user, you cannot acess /data/data path..
In my case i’m using the path:
context.getFilesDir().getAbsolutePath().replace("files", "databases") + File.separator
http://androiddev.orkitra.com/?p=13793
就是說,androi4.2中引入了多使用者機制,普通使用者無法訪問根目錄下的/data/data目錄,因而無法建立資料庫檔案。而我的安卓模擬器確實是最新的4.2版本,因此就會有這種問題。
知道原因就很好解決了,按照上面的方法使用context.getFilesDir().getAbsolutePath()擷取絕對路徑即可。