Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack

How to access Context to create a file directory in Jetpack Compose?


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.

fun createDir() {

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



@Composable
fun someFunction() {

     ...        

     Button(
        onClick = {
            createDir()
        }   
      ) { ... }

Solution

  • Have you tried using LocalContext?

    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)
          }   
        ) { ... }