Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading