In one step, I will be prompted to pick a folder at external SD card. I do and pick a folder.
public void GetPermission(){
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
startActivityForResult(intent, 42);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (resultCode != RESULT_OK)
return;
Uri treeUri = resultData.getData();
getContext().getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
later I download a zip-file (by asynctask) to picked folder from the Internet. Just to test I download the file to the picked folder with success through the following routine
uri_ext = Uri.parse(uri_string);
URLConnection conexion = url_download.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url_download.openStream());
OutputStream output = null;
DocumentFile pickedDir = DocumentFile.fromTreeUri(the_context, uri_ext);
DocumentFile newFile = pickedDir.createFile("application/zip", zipname);
output = the_context.getContentResolver().openOutputStream(newFile.getUri());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
if (isCancelled()) break;
}
output.flush();
output.close();
input.close();
after that the file exists in the picked folder. The download should not take place in the picked folder, but in a subfolder of the picked folder. So I create a subfolder with the following code:
DocumentFile new_Dir = DocumentFile.fromTreeUri(context, uri_ext);
new_Dir.createDirectory("new_subfolder");
uri_string = uri_string + "%2Fnew_subfolder");
// uri_string = uri_string + "/new_subfolder"); also checked
// no other code, nothing else
after that the subfolder is present. Now I try to load the zip-file from the internet into the new subfolder with the exact same code (except for the uri path from varibale uri_string) from above. Result: the download to the new subfolder does not work.
Why? What am I doing wrong? What do I have to change?
After some tests I found an easy solution:
documentDirectory = DocumentFile.fromTreeUri(the_context, Uri.parse(path));
documentDirectory.createDirectory("new_subfolder");
documentDirectory = documentDirectory.findFile("new_subfolder");
after the last line it then continues with the above code and everything works. Maybe it was just too easy. :)