Problem description
This exception occurs when SQLite cannot open a database.
Solution
This exception occurs when SQLite cannot open a database. It is because the database file does not exist, the read and write permissions are not granted, or special permissions are required for the file. We recommend that you check whether the required permissions are granted and whether the file path is correct.
Sample code
To read files stored in the external storage, you must add permissions to the manifest file:
<uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>For versions earlier than Android 6.0, authorization takes place during installation and update. For Android 6.0 and later, authorization is performed during runtime. To obtain permissions during runtime, you must apply for permissions from users:
// 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.
}
}Then, confirm that the permissions are granted and handle the exception.
@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;
}
}References
https://developer.android.com/reference/android/database/sqlite/SQLiteCantOpenDatabaseException.html
https://developer.android.com/training/permissions/requesting.html#perm-check (Android 6.0 authorization check methods)
https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous (Common and risky permissions)