Search code examples
androidkotlinviewmodel

Referencing SD card from Kotlin


I am writing an Android app on the Jetpack Composable platform with Android Studio. I need to read and write files on an SD card that is installed in the tablet. I can define the path to the card as follows:

private val externalStorageVolumes = context.let { ContextCompat.getExternalFilesDirs(it.applicationContext, null) }

private val sdCardStorage = externalStorageVolumes[1]

The problem is: I want to access the card from a view's ViewModel, but as you can see I need to pass a reference to a context. Apparently one should not refence any context from a ViewModel, as that can lead to memory leaks.

Is the any way to read and write to a SD card from a ViewModel that does not need a context? Thanks!


Solution

  • Apparently one should not refence any context from a ViewModel, as that can lead to memory leaks

    That is what AndroidViewModel is for. It mediates access to the Application, which is a singleton Context safe to use from a ViewModel.

    Even better is to have your data storage logic be managed by a singleton repository class, as part of a layered architecture. You would have the repository get access to the Application singleton via dependency inversion (Dagger/Hilt, Koin, etc.).