简体   繁体   English

从 MVVM 存储库写入 filesDir 的权威 Android 指南(2022 年)

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

I have the seemingly simple plan to write a JSON file to internal storage while obeying the MVVM architecture.我有一个看似简单的计划,即在遵守 MVVM 架构的同时将 JSON 文件写入内部存储。 Unfortunately, almost all the focus on StackOverflow, tutorials and the official documentation seems to be on external storage or databases.不幸的是,几乎所有对 StackOverflow、教程和官方文档的关注似乎都集中在外部存储或数据库上。 The rest ignores MVVM or is generally outdated. rest 忽略 MVVM 或通常已过时。
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.经过大量实验,文件目录不知何故为filesDir ,文件系统被声明为只读,而我处于普遍混乱的 state 中,我确定了一个解决方案,您可以在下面找到答案。

Problem问题

I can't decide if my solution below is reasonable or if it has any major drawbacks or violations of MVVM I overlooked.我无法确定我下面的解决方案是否合理,或者它是否有任何重大缺陷或违反了我忽略的 MVVM。 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!请帮我把它变成一个最新的行业标准指南,适合像我这样的初学者!

My solution我的解决方案

  1. Create a Repository singleton (Java style) using a companion object with var FILE: File? = null使用伴随的 object 和var FILE: File? = null var FILE: File? = null

  2. A class MyApp: Application() and inside its onCreate() method:一个class MyApp: Application()及其onCreate()方法:
    Repository.FILE = File(filesDir, "entries.json") . Repository.FILE = File(filesDir, "entries.json")

Don't forget to set this application class as android:name in the AndroidManifest!不要忘记在 AndroidManifest 中将此应用程序 class 设置为android:name

  1. A private var file = Repository.FILE!! private var file = Repository.FILE!! in the "DAO" (my data layer).在“DAO”(我的数据层)中。 I feel safe in casting file as non-null because Application().onCreate() is always called first on startup.我觉得将file转换为非空是安全的,因为Application().onCreate()总是在启动时首先被调用。

  2. Use the file variable for actual I/O.file变量用于实际 I/O。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM