文档

android_database_sqlite_SQLiteCantOpenDatabaseException

问题分析

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

解决方案

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

代码示例

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

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

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

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {
    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {
        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed, we can request the permission.
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

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

@Override
  public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
      switch (requestCode) {
         case WRITE_REQUEST_CODE:
           if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
             //Permission granted.
             //Continue with writing files...
           }
         else{
             //Permission denied.
           }
          break;
      }
  }

参考文献

  • 本页导读 (0)
文档反馈