Is it a normal thing to write app data in Android using file API instead of room database in Kotlin?

huangapple go评论61阅读模式
英文:

Is it a normal thing to write app data in Android using file API instead of room database in Kotlin?

问题

从Android数据库中看,似乎有以下存储应用数据到文件的方式(而不是存储在内存中):

  1. Room数据库
  2. 共享首选项
  3. 文件流

共享首选项仅适用于小型键值对,而不适用于应用程序数据。

YouTube和Google似乎建议使用Room数据库来进行应用程序数据管理。然而,问题在于大部分文档要么是关于Jetpack,要么是关于较早版本的Kotlin与Room数据库。当我尝试在Kotlin中使用较新版本的Android SDK时,它会不断出现错误,甚至导致我放弃使用。

对于应用程序数据,通过文件流API进行写入是一种正常的做法吗?
这些应用程序数据是JSON文本数据。

https://developer.android.com/training/data-storage/app-specific

英文:

From Android database it seems there are following ways of storing app data in a file(permanent instead of memory storage):

  1. Room database
  2. Shared preferences
  3. File stream

Shared preferences is just for small key value pair and not for app data.

YouTube and Google seem to suggest room database is the best option for app data management. The problem though is that most of it is either in jetpack or older version of room database with Kotlin. When I try to use newer version of Android SDK with kotlin then it just keeps crashing with endless errors to the point of giving it up.

Is writing by stream file API for app data a normal thing?
The app data is JSON text data.

https://developer.android.com/training/data-storage/app-specific

答案1

得分: 1

使用任何方式存储数据都是正常的。但出于特定原因,某些方法可能更可取。

文件的问题在于您应该准备好处理不同的错误。例如,如果用户清除了应用程序的缓存,文件可能会损坏或过时。此外,您必须在读取文件之前检查文件是否存在,并在每次更改后将新数据重写到文件中。

Room 可以帮助您在不编写冗长代码的情况下实现相同的结果。它应该与新的 Android SDK 配合使用,所以如果您显示给我们错误(例如,当您更改实体类而不删除旧数据库时,常见问题就会出现。在这种情况下,删除应用程序的用户数据可能有所帮助)

如果您的应用程序数据不是很大,您还可以将其序列化(或简单地转换为字符串)并存储在 SharedPreferences 中。

英文:

It's normal to use any way to store data. But for specific reasons some of approaches may be more preferable.

Problems with files is that you should be prepared to handle different errors. For example if user cleared cache of app, file became corrupted or outdated. Also you must check if file exists before reading it and after every change rewrite new data to it.

Room helps to achieve same result using less boilerplate code. It should work with new Android SDK, so maybe we can help if you show us error (for example there is common problem when you change your Entity class without deleting old database. In this case removing user's data of app can help)

If your app data isn't big you also can make it serializable (or simply convert to string) and store in SharedPreferences

huangapple
  • 本文由 发表于 2023年6月26日 00:34:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551436.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定