Home > database >  How to create a directory with a function outside of MainActivity class in Kotlin?
How to create a directory with a function outside of MainActivity class in Kotlin?

Time:11-06

I am using this createDir() function to create directories but to call it from Composable functions I need to take function outside of MainActivity unfortunately because of applicationContext it does not work.

class MainActivity : ComponentActivity() {


 fun createDir(){

    val path = applicationContext.filesDir
    val letDirectory = File(path, "TestDir")
    val resultMkdirs: Boolean = letDirectory.mkdirs()

 }

...

}

This is what I want to do.

class MainActivity : ComponentActivity() {

  ...

}




 fun createDir(){

    val path = applicationContext.filesDir
    val letDirectory = File(path, "TestDir")
    val resultMkdirs: Boolean = letDirectory.mkdirs()

 }



 @Composable
 fun someFunction(){

    ...        

     Button(),

       onClick={

          createDir()

          }) {

             Text( ... )
               
            }
  }

CodePudding user response:

Have you tried using the Local context?

LocalContext.current

Your modified code:

fun createDir(context: Context){

    val path = context.filesDir
    val letDirectory = File(path, "TestDir")
    val resultMkdirs: Boolean = letDirectory.mkdirs()

}



@Composable
fun someFunction(){

    ...

    val context = LocalContext.current
    
    Button(),

    onClick={

        createDir(context)

    }) {

        Text( ... )

    }
}
  • Related