1

I am trying to copy files from DOCUMENTS folder to cache folder in Android 10

Since Android 10, MEDIASTORE has to be used, so I wrote the code referring to the data in the link below.

Create/Copy File in Android Q using MediaStore

The file exists but returns 'No file found' Log

How do I copy or read files that my app did not create?

File deviceDB = new File(getDatabasePath(Define.DBNAME).toString() + ".db");

Uri contentUri = MediaStore.Files.getContentUri("external");
String selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?";
String[] selectionArgs = new String[]{Environment.DIRECTORY_DOCUMENTS + "/" + Define.BACKUP_DIR + "/"};
Cursor cursor = getContentResolver().query(contentUri, null, selection, selectionArgs, null);
Uri uri = null;

if (cursor.getCount() == 0) {
    Log.i("debug","No file found");
} else {
    while (cursor.moveToNext()) {
        String fileName = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME));

        if (fileName.equals(dbName + ".db")) {
            long id = cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            uri = ContentUris.withAppendedId(contentUri, id);
            break;
        }
    }

    if (uri == null) {
        Log.i("debug","uri == null");
    } else {

        InputStream inputStream = getContentResolver().openInputStream(uri);
        int size = inputStream.available();
        byte[] bytes = new byte[size];
        inputStream.read(bytes);

        OutputStream output = new FileOutputStream(deviceDB);
        output.write(bytes);
        output.flush();

        inputStream.close();
    }
}
swiftbegineer
  • 329
  • 1
  • 9
  • You use ACTION_OPEN_DOCUMENT_,TREE to let the user choose the Documents folder. Use further SAF to list the files and copy. – blackapps Oct 30 '21 at 04:39

0 Answers0