In my Android Studio project I want to implement a function, where 3 files should get exported. So I want the user to choose a directory and enter the name for a new directory, in which the files are going to be stored.
Right now, I already have an intent which lets the user choose, where to place the new folder and how to name the new folder:
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(DocumentsContract.Document.MIME_TYPE_DIR);
intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.folder_backup));
startActivityForResult(intent, REQUEST_CODE_SAVE_BACKUP);
In the onActivityResult method, I tried to save the 3 files. Here is the code:
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_SAVE_BACKUP
&& resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
String dbFileName = ExampleDatabase.DB_NAME;
List<String> dbComponentsNames = new ArrayList<>();
dbComponentsNames.add(dbFileName);
dbComponentsNames.add(dbFileName + "-shm");
dbComponentsNames.add(dbFileName + "-wal");
try {
for (int i = 0; i < dbComponentsNames.size(); i++) {
uri = Uri.parse(uri.toString() + "%2F" + dbComponentsNames.get(i));
File dbComponent = getActivity().getDatabasePath(dbComponentsNames.get(i));
byte[] byteArray = new byte[(int) dbComponent.length()];
FileInputStream fileInputStream = new FileInputStream(dbComponent);
fileInputStream.read(byteArray);
ParcelFileDescriptor pfd = getActivity().getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write(byteArray);
pfd.close();
}
} catch (Exception e) {
}
}
}
}
My idea was to get the URI from the created folder and just append the file names to that URI, so these files get stored in the newly created folder. I also found out, that a \
in the URI is replaced by %2F
but this doesn't matter. Does anyone know, how to achieve saving multiple files without using MediaStore?