我目前正在从firestore中检索数据,并将检索到的数据保存到一个列表中,该列表用于在内部存储中创建缓存文件。当应用程序启动时,我检查网络,如果没有网络,我使用缓存中的数据来填充回收视图。这很好用,但是我想在离线时执行CRUD操作,并且我很难找到一种方法来实现这一点。
这是从firestore中检索数据并调用以创建缓存文件时的代码。
override fun getFromFirestore(context: Context, callback: (MutableList<PostFirestore>) -> Unit) {
db.firestoreSettings = settings
val notesList = mutableListOf<PostFirestore>()
try {
db.collection("DiaryInputs")
.addSnapshotListener { snapshot, e ->
notesList.clear()
if (snapshot != null && !snapshot.isEmpty) {
for (doc in snapshot.documents) {
val note = doc.toObject(PostFirestore::class.java)
notesList.add(note!!)
}
cacheHelper.createCachedFile(context, notesList)
callback(notesList)
} else {
//Refreshing the RV and cache if firestore is empty.
cacheHelper.deleteCachedFile(context)
callback(notesList)
}
}
} catch (e: Exception){
Log.d(TAG, "Failure", e)
}
}下面是创建缓存文件的方式:
@Throws(IOException::class)
override fun createCachedFile(context: Context, notesList: MutableList<PostFirestore>) {
val outputFile = File(context.cacheDir, "cache").toString() + ".tmp"
val out: ObjectOutput = ObjectOutputStream(
FileOutputStream(
File(outputFile)
)
)
out.writeObject(notesList)
out.close()
}这是数据类PostFirestore
class PostFirestore: Serializable {
var id: String? = null
var diaryInput: String? = null
var temp: String? = null
var creationDate: String? = null
constructor() {}
constructor(id: String, diaryInput: String, temp: String, creationDate: String) {
this.id = id
this.diaryInput = diaryInput
this.temp = temp
this.creationDate = creationDate
}}
我应该怎么做才能将一些东西添加到缓存文件"cache.tmp“中,而不是覆盖它?以及如何编辑/删除存储在缓存文件中的列表中的内容?
发布于 2020-12-30 02:33:12
Firestore自动处理离线读写。请参阅handling read and writes while offline上的文档。
如果你不想依赖它,你必须在你自己的持久层中复制它。这包括(但可能不限于):
根据您的场景,可能会有更多的步骤。如果你被某个特定的步骤卡住了,我建议你回复一个新的问题,并提供关于该步骤的具体细节。
https://stackoverflow.com/questions/65493116
复制相似问题