I'm working on backup and restore SQLite Database to cloud server. I've completed the backup code and it works. However, I have a problem when I'm trying to restore it. The problem is, on Android 11, the Environment.DIRECTORY_DOWNLOADS
is in Android/data/package/files/Download, but somehow I cannot access or write to Environment.DIRECTORY_DOWNLOADS
, and I don't know why. Here's my code (the download from cloud method, it succeeds).
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(response.body().getPath());
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalFilesDir(getApplicationContext(), Environment.DIRECTORY_DOWNLOADS, sharedPreference.getUser().getEmail() + ".db");
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle(sharedPreference.getUser().getEmail() + ".db");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
Long downloadReference = manager.enqueue(request);
When I'm trying to access them, I cannot access the Environment.DIRECTORY_DOWNLOADS
. Here is the code
File internal = new File(Environment.DIRECTORY_DOWNLOADS);
if (internal.canRead()) {
File currentDB = new File("/data/data/" + getPackageName() + "/databases/", DBHelper.DATABASE_NAME);
File backupDB = new File(internal, sharedPreference.getUser().getEmail() + ".db");
Toast.makeText(getApplicationContext(),backupDB.toString(),Toast.LENGTH_SHORT).show();
if (backupDB.exists()) {
FileChannel src = new FileInputStream(backupDB).getChannel();
FileChannel dst = new FileOutputStream(currentDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), backupDB.toString(), Toast.LENGTH_SHORT).show();
} else {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error, file not exist!", Toast.LENGTH_SHORT).show();
}
} else {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error, cannot read the directory!", Toast.LENGTH_SHORT).show();
}