Thursday, 27 August 2020

Rename file of the Mediastore which is created by app in android 10. Working on Android API 30 but shows error in API 29

Here, this renameFile(..) func is working in Android API 30. But, it is not working in Android API 29 and shows the error like : java.lang.IllegalArgumentException: Movement of content://media/external/file/116 which isn't part of well-defined collection not allowed

Note: The file is removed from the AppFolder folder of MediaStore after getting this exception.

Uri extUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
String relativeLocation = Environment.DIRECTORY_DOWNLOADS + File.separator + "AppFolder";

function renameFile(...)

boolean renameFile(Context context, String newName, String displayName) {

    try {
        Long id = getIdFromDisplayName(displayName);
        ContentResolver contentResolver = context.getContentResolver();
        Uri mUri = ContentUris.withAppendedId(extUri, id);
        ContentValues contentValues = new ContentValues();

        contentValues.put(MediaStore.Files.FileColumns.IS_PENDING, 1);
        contentResolver.update(mUri, contentValues, null, null);

        contentValues.clear();
        contentValues.put(MediaStore.Files.FileColumns.DISPLAY_NAME, newName);
        // contentValues.put(MediaStore.Files.FileColumns.MIME_TYPE, "files/pdf");
        // contentValues.put(MediaStore.Files.FileColumns.RELATIVE_PATH, relativeLocation);
        // contentValues.put(MediaStore.Files.FileColumns.TITLE, "SomeName");
        // contentValues.put(MediaStore.Files.FileColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
        // contentValues.put(MediaStore.Files.FileColumns.DATE_TAKEN, System.currentTimeMillis());
        contentValues.put(MediaStore.Files.FileColumns.IS_PENDING, 0);
        contentResolver.update(mUri, contentValues, null, null);
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return false;
}

function getIdFromDisplayName(...)

@RequiresApi(api = Build.VERSION_CODES.Q)
Long getIdFromDisplayName(String displayName) {
    String[] projection;
    projection = new String[]{MediaStore.Files.FileColumns._ID};

    // TODO This will break if we have no matching item in the MediaStore.
    Cursor cursor = getContentResolver().query(extUri, projection,
            MediaStore.Files.FileColumns.DISPLAY_NAME + " LIKE ?", new String[]{displayName}, null);
    assert cursor != null;
    cursor.moveToFirst();

    if (cursor.getCount() > 0) {
        int columnIndex = cursor.getColumnIndex(projection[0]);
        long fileId = cursor.getLong(columnIndex);

        cursor.close();
        return fileId;
    }
    return null;
}

function savePDFFile(...) public static Uri savePDFFile(final Context context, File file, final String displayName) throws IOException {

    final ContentValues contentValues = new ContentValues();
    contentValues.put(MediaStore.Files.FileColumns.DISPLAY_NAME, displayName + ".pdf");
    contentValues.put(MediaStore.Files.FileColumns.MIME_TYPE, "files/pdf");
    contentValues.put(MediaStore.Files.FileColumns.RELATIVE_PATH, relativeLocation);
    contentValues.put(MediaStore.Files.FileColumns.TITLE, "SomeName");
    contentValues.put(MediaStore.Files.FileColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
    contentValues.put(MediaStore.Files.FileColumns.DATE_TAKEN, System.currentTimeMillis());
    final ContentResolver resolver = context.getContentResolver();
    OutputStream stream = null;
    Uri uri = null;

    Uri isUriExist = getUriFromDisplayName(context, displayName + ".pdf");

    try {
        if (isUriExist == null) {
            uri = resolver.insert(extUri, contentValues);
        } else {
            uri = isUriExist;
        }
        if (uri != null) {
            ParcelFileDescriptor pfd;
            try {
                pfd = context.getContentResolver().openFileDescriptor(uri, "w");
                assert pfd != null;
                FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());

                byte[] buf = new byte[4 * 1024];
                int len;
                FileInputStream in = new FileInputStream(file);
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.close();
                in.close();
                pfd.close();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            contentValues.clear();
            contentValues.put(MediaStore.Files.FileColumns.IS_PENDING, 0);
            context.getContentResolver().update(uri, contentValues, null, null);
            stream = resolver.openOutputStream(uri);
            if (stream == null) {
                throw new IOException("Failed to get output stream.");
            }

        }
        return uri;


    } catch (IOException e) {
        // Don't leave an orphan entry in the MediaStore
        resolver.delete(uri, null, null);
        return null;
    } finally {
        if (stream != null) {
            stream.close();
        }
    }

}

function getUriFromDisplayName(...)

public static Uri getUriFromDisplayName(Context context, String displayName) {

    String[] projection;
    projection = new String[]{MediaStore.Files.FileColumns._ID};

    // TODO This will break if we have no matching item in the MediaStore.
    Cursor cursor = context.getContentResolver().query(extUri, projection,
            MediaStore.Files.FileColumns.DISPLAY_NAME + " LIKE ?", new String[]{displayName}, null);
    assert cursor != null;
    cursor.moveToFirst();

    if (cursor.getCount() > 0) {
        int columnIndex = cursor.getColumnIndex(projection[0]);
        long fileId = cursor.getLong(columnIndex);

        cursor.close();
        return Uri.parse(extUri.toString() + "/" + fileId);
    } else {
        return null;
    }

}

function deleteFileUsingDisplayName(...)

public static boolean deleteFileUsingDisplayName(Context context, String displayName) {

    Uri uri = getUriFromDisplayName(context, displayName);
    if (uri != null) {
        final ContentResolver resolver = context.getContentResolver();
        String[] selectionArgsPdf = new String[]{displayName};

        try {
            resolver.delete(uri, MediaStore.Files.FileColumns.DISPLAY_NAME + "=?", selectionArgsPdf);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            // show some alert message
        }
    }
    return false;

}

function getExternalPDFFileList(...)

public static ArrayList<FileModel> getExternalPDFFileList(Context context) {

    ContentResolver cr = context.getContentResolver();

    String[] projection = {MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DISPLAY_NAME};
    String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
            + MediaStore.Files.FileColumns.MEDIA_TYPE;
    String[] selectionArgs = null;
    String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
    String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
    String[] selectionArgsPdf = new String[]{mimeType};

    Cursor cursor = cr.query(extUri, projection, selectionMimeType, selectionArgsPdf, null);

    assert cursor != null;
    ArrayList<FileModel> uriList = new ArrayList<>();
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        int columnIndex = cursor.getColumnIndex(projection[0]);
        long fileId = cursor.getLong(columnIndex);
        Uri fileUri = Uri.parse(extUri.toString() + "/" + fileId);
        String displayName = cursor.getString(cursor.getColumnIndex(projection[1]));
        uriList.add(new FileModel(displayName, fileUri));
    }
    cursor.close();
    return uriList;
}


from Rename file of the Mediastore which is created by app in android 10. Working on Android API 30 but shows error in API 29

No comments:

Post a Comment