kotlin doesn’t show files in the directory

You can check the required permissions programmatically by calling this method

fun checkPermissions()
{
    this.onPermissionGranted = onPermissionGranted

    val ungrantedPermissions = requiredPermissionsStillNeeded()

    if (ungrantedPermissions.isEmpty()) {
        // All permission granted, you can list your files...
    } else {
        ActivityCompat.requestPermissions(activity, ungrantedPermissions, 1)
    }
}

This function calls this method

private fun requiredPermissionsStillNeeded(): Array<String>
{
    val permissions = HashSet<String>()

    for (permission in getRequiredPermissions()) {
        permissions.add(permission)
    }

    val i = permissions.iterator()

    while (i.hasNext()) {
        val permission = i.next()
        if (ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED) {
            i.remove()
        }
    }

    return permissions.toTypedArray()
}

private fun getRequiredPermissions(): Array<String>
{
    var permissions: Array<String>? = null

    try {
        permissions = activity.packageManager.getPackageInfo(activity.packageName, PackageManager.GET_PERMISSIONS).requestedPermissions
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
    }

    return permissions?.clone() ?: arrayOf()
}

Lastly, you’ll need to override this method in your activity. It is called recursively until your user has granted all the permissions needed by the app.

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    checkPermissions()
}

After that, your app should be able to list the files in the folder.

EDIT

These are all functions that check whether the users have granted you the required permissions.

You should add them to your MainActivity class and edit your onCreate method like this

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
 
    println()
    //readSongs(dir, ext)
 
    checkPermissions() 
}

And then call your list file function in checkPermissions() like this

fun checkPermissions()
{
    this.onPermissionGranted = onPermissionGranted

    val ungrantedPermissions = requiredPermissionsStillNeeded()

    if (ungrantedPermissions.isEmpty()) {
        val gpath: String = Environment.getExternalStorageDirectory().absolutePath
        val spath = "Music"
        val fullpath = File(gpath + File.separator + spath)
        println("fullpath")
        println(fullpath)
        imageReaderNew(fullpath)
    } else {
        ActivityCompat.requestPermissions(activity, ungrantedPermissions, 1)
    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top