My movement looks like this:
private void moveSelectedItemsToFolder(String destinationFolder) {
List<Integer> selectedItems = mediaAdapter.getSelectedItems();
if (selectedItems.isEmpty()) {
Toast.makeText(this, "No items selected", Toast.LENGTH_SHORT).show();
return;
}
boolean allFilesMoved = true;
List<String> failedFiles = new ArrayList<>();
for (int position : selectedItems) {
String sourcePath = mediaPaths.get(position);
File sourceFile = new File(sourcePath);
File destinationFile = new File(destinationFolder, sourceFile.getName());
// Определение типа файла
Uri uri = isVideoList.get(position)
? MediaStore.Video.Media.EXTERNAL_CONTENT_URI
: MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
// Проверка, существует ли файл с таким же именем в целевой папке
if (destinationFile.exists()) {
Toast.makeText(this, "File already exists: " + destinationFile.getName(),
Toast.LENGTH_SHORT).show();
allFilesMoved = false;
failedFiles.add(sourceFile.getName());
continue;
}
// Попытка перемещения файла
boolean moved = sourceFile.renameTo(destinationFile);
if (moved) {
// Удаление старого файла из MediaStore
getContentResolver().delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{sourcePath});
// Добавление нового файла в MediaStore
MediaScannerConnection.scanFile(this, new String[]{destinationFile.getAbsolutePath()}, null, null);
} else {
// Попытка копирования и удаления при неудачном перемещении
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Files.copy(sourceFile.toPath(), destinationFile.toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Files.delete(sourceFile.toPath());
}
// Удаление старого файла из MediaStore
getContentResolver().delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{sourcePath});
// Добавление нового файла в MediaStore
MediaScannerConnection.scanFile(this, new String[]
{destinationFile.getAbsolutePath()}, null, null);
} catch (IOException e) {
e.printStackTrace();
allFilesMoved = false;
failedFiles.add(sourceFile.getName());
}
}
}
if (allFilesMoved) {
Toast.makeText(this, "Files moved successfully", Toast.LENGTH_SHORT).show();
} else {
StringBuilder failedFilesMessage = new StringBuilder("Some files could not be
moved:");
for (String fileName : failedFiles) {
failedFilesMessage.append("n").append(fileName);
}
Toast.makeText(this, failedFilesMessage.toString(), Toast.LENGTH_LONG).show();
}
}
For example, the video moves, but the image does not. Can anyone help me with this problem, please, professional developers!