0

I am trying to create folder in Android internal storage. For that I am using below code

val path = File(getExternalFilesDir(null),"MyFolder")  

But it is creating folder in Android directory inside app package name under files directory like this: Android/data/com.app.myapp/files/MyFolder. I don't want to create folder like this rather I want to create folder in internal storage like WhatsApp creates.

How can I do this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Digvijay
  • 2,887
  • 3
  • 36
  • 86
  • Use this: `context.getFilesDir();` – glzlaohuai Dec 10 '20 at 11:50
  • i have used like this `val path = File(applicationContext.filesDir,"MyFolder")` but its not creating folder. – Digvijay Dec 10 '20 at 12:18
  • Those statements do not create a folder. To create a folder use File:mkdir() or File:mkdirs(). Check the return value to see if it is really created. Only call those functions if the folder does not exist yet. – blackapps Dec 10 '20 at 13:39
  • "I want to create folder in internal storage like Whatsapp creates" -- that is no longer going to be possible, as of next year, when your `targetSdkVersion` needs to be raised to 30. – CommonsWare Dec 10 '20 at 13:39
  • @CommonsWare, that means now onwards app specific folders can only be created under app package name. – Digvijay Dec 10 '20 at 15:33
  • If you want to create the directory yourself, then yes. What Google would like you to do is use the Storage Access Framework (e.g., `ACTION_OPEN_DOCUMENT_TREE`), and let the *user* decide where on the *user's* device (or in the *user's* preferred cloud storage service) that your app should store the *user's* content. – CommonsWare Dec 10 '20 at 16:23

1 Answers1

0

So easy, for API level 29 or later:

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()
}
Sam Chen
  • 7,597
  • 2
  • 40
  • 73
  • On using above solution app is crashing in android version 6 but working fine in android version 10 why so.`java.lang.SecurityException: Permission Denial: writing com.android.providers.media.MediaProvider uri content://media/external/file from pid=26437, uid=10240 requires android.permission.WRITE_EXTERNAL_STORAGE, or grantUriPermission()` showing this logcat. – Digvijay Dec 10 '20 at 20:42
  • @Digvijay I've said that "for API level 29 or later", API level 29 is Android version 10 (Q). The new way of storing file anounced by Google in 2019: https://youtu.be/UnJ3amzJM94. For older device you can just use the old method. Also check this: https://stackoverflow.com/questions/59511147/create-copy-file-in-android-q-using-mediastore/62879112#62879112。 – Sam Chen Dec 10 '20 at 21:13