androidandroid-storage

How to save Document file in external storage after android API LEVEL28 With Android SAF(Storage Access Framework))


This Code Works Fine With Media Files I want a solution For Document Files

I Don't Know how to put contentValues For Document Files

fun getFile(fileName: String): File? {
    with(sharePrefHelper.app){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val values = ContentValues()
            // Here is My Question That what should i Do Here Because this is for document not for image
            values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
            // for MIME_TYPE "image/jpg" this is working
            values.put(MediaStore.Images.Media.MIME_TYPE, "text/csv")
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/Donny")
            contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)?.let {
                it.path?.let { finalPath ->
                    return File(finalPath)
                }
            }
        } else {
            val directory: File = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/Donny")
            if (!directory.exists()){
                directory.mkdirs()
            }
            return File(directory, fileName)
        }
        return null
    }
}

This Code Works Fine with media Files

My Question Here is How to save documents like CSV File in outer folder of android device


Solution

  • EDIT :

    Well well well, I'm still trying to add anytype of file in the "download" directory. Personnaly, I'm trying to copy a file from my assetFolder and paste it to the "Download" folder. I haven't succeeded yet. However, I can currently CREATE anytype of file in that folder, it's working with the method below. I hope this can help you.

    Here is my code :

        public void saveFileToPhone(InputStream inputStream, String filename) {
        OutputStream outputStream;
        Context myContext = requireContext();
        try {
            if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.Q){
                ContentResolver contentResolver = requireContext().getContentResolver();
                ContentValues contentValues = new ContentValues();
                contentValues.put(MediaStore.Downloads.DISPLAY_NAME,filename);
                contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
                Uri collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
                Uri fileUri = contentResolver.insert(collection, contentValues);
                outputStream = contentResolver.openOutputStream(Objects.requireNonNull(fileUri));
                Objects.requireNonNull(outputStream);
    
            }
        }catch (FileNotFoundException e) {
    
            e.printStackTrace();
        }
    }