Search code examples
androidkotlinandroid-fileandroid-storage

create a folder in /storage/emulated/0


I would like to create a directory in /storage/emulated/0/ and a save a file there.Since the "getExternalStorageDir()" & "getExternalPublicStorageDir()" are Depreciated I don't know how to implement it. I have gone through most of the questions and answers but they are all either outdated/open. All I want is a way to access the "storage/emulated/0/" path.

val extStorageDirectory = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
val folder = File(extStorageDirectory, "Work Logs")
folder.mkdir()

The above code creates a folder in "Android/data/com.xxx.xxx/"


Solution

  • Easy with MediaStore.

    binding.createFolderButton.setOnClickListener {
        val values = ContentValues()
    
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_DOCUMENTS}/myFolder/")       //folder name
    
        contentResolver.insert(MediaStore.Files.getContentUri("external"), values)
    
        Toast.makeText(this, "\"myFolder\" created", Toast.LENGTH_SHORT).show()
    }