I use the following code to export the database file to the phone memory. It works fine on Android 24 , but on API 28 it only gives an empty file:
public void exportDatabse() {
try {
if (sd.canWrite()) {
String backupDBPath = "nameBCK.db";
File currentDB = new File(MainActivity.this.getDatabasePath("dataBaseName.db").getPath());
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(this,getString(R.string.stSuccess2),
Toast.LENGTH_LONG).show();
}
}
else {
REQUEST_TYPE=0;
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);}
} catch (Exception e) {
Toast.makeText(this,getString(R.string.stFaild),Toast.LENGTH_LONG).show();
}
}
And also I use onRequestPermissionsResult to request permission to write to storage.
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (REQUEST_TYPE==0) exportDatabse();
if (REQUEST_TYPE==1) importDB();
} else {
if (REQUEST_TYPE==0) Toast.makeText(this,getString(R.string.stFaild2),Toast.LENGTH_LONG).show();
if (REQUEST_TYPE==1) Toast.makeText(this,getString(R.string.stFaild3),Toast.LENGTH_LONG).show();
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
default:
throw new IllegalStateException("Unexpected value: " + requestCode);
}
}