写了个小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 database 02-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()获取绝对路径即可。