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

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!

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 :

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

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