全部产品

android_database_sqlite_SQLiteCantOpenDatabaseException

更新时间:2017-06-07 13:26:11

问题分析:

SQLite无法打开数据库时抛出此类异常。

解决方案:

SQLite无法打开数据库抛出此类异常是因为读写的数据库文件不存在或者没有申请到正确的读写权限或者这个文件的权限比较特别,建议检查是否申请到了正确的权限、并且文件路径正确。

代码示例:

如果需要读取外部存储器上的文件需要在Manifest添加权限

  1. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

在Android6.0以前申请权限时,用户在安装和更新时会进行授权。Android6.0以后会在运行期用户进行授权。为了在运行期获取权限,首先需要向用户请求权限:

  1. // Here, thisActivity is the current activity
  2. if (ContextCompat.checkSelfPermission(thisActivity,
  3. Manifest.permission.READ_CONTACTS)
  4. != PackageManager.PERMISSION_GRANTED) {
  5. // Should we show an explanation?
  6. if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
  7. Manifest.permission.READ_CONTACTS)) {
  8. // Show an expanation to the user *asynchronously* -- don't block
  9. // this thread waiting for the user's response! After the user
  10. // sees the explanation, try again to request the permission.
  11. } else {
  12. // No explanation needed, we can request the permission.
  13. ActivityCompat.requestPermissions(thisActivity,
  14. new String[]{Manifest.permission.READ_CONTACTS},
  15. MY_PERMISSIONS_REQUEST_READ_CONTACTS);
  16. // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
  17. // app-defined int constant. The callback method gets the
  18. // result of the request.
  19. }
  20. }

然后确认是否权限通过,做业务处理。

  1. @Override
  2. public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
  3. switch (requestCode) {
  4. case WRITE_REQUEST_CODE:
  5. if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
  6. //Permission granted.
  7. //Continue with writing files...
  8. }
  9. else{
  10. //Permission denied.
  11. }
  12. break;
  13. }
  14. }

参考文献:

  1. https://developer.android.com/reference/android/database/sqlite/SQLiteCantOpenDatabaseException.html
  2. http://stackoverflow.com/questions/17034511/android-database-sqlite-sqlitecantopendatabaseexception-unknown-error-code-14
  3. https://developer.android.com/training/permissions/requesting.html#perm-check (安卓6.0授权检查方式)4.https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous (普通权限及危险权限说明)