Definitive Android guide to writing to filesDir from MVVM repository (in 2022)

Viewed 18

I have the seemingly simple plan to write a JSON file to internal storage while obeying the MVVM architecture. Unfortunately, almost all the focus on StackOverflow, tutorials and the official documentation seems to be on external storage or databases. The rest ignores MVVM or is generally outdated.
After a lot of experimentation where somehow filesDir was null, the filesystem was declared as read-only, and I was in a state of general confusion, I settled on a solution which you find as answer below.

Problem

I can't decide if my solution below is reasonable or if it has any major drawbacks or violations of MVVM I overlooked. I am absolutely missing some kind of authoritative guide for such a basic task, so I tried to create one here. Please help me make this an up-to-date, industry standard guide for beginners like me!

1 Answers

My solution

  1. Create a Repository singleton (Java style) using a companion object with var FILE: File? = null

  2. A class MyApp: Application() and inside its onCreate() method:
    Repository.FILE = File(filesDir, "entries.json").

Don't forget to set this application class as android:name in the AndroidManifest!

  1. A private var file = Repository.FILE!! in the "DAO" (my data layer). I feel safe in casting file as non-null because Application().onCreate() is always called first on startup.

  2. Use the file variable for actual I/O.

Related