首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在android中将对象缓存到文件(kotlin)

问在android中将对象缓存到文件(kotlin)
EN

Stack Overflow用户
提问于 2020-12-29 21:42:07
回答 1查看 492关注 0票数 0

我目前正在从firestore中检索数据,并将检索到的数据保存到一个列表中,该列表用于在内部存储中创建缓存文件。当应用程序启动时,我检查网络,如果没有网络,我使用缓存中的数据来填充回收视图。这很好用,但是我想在离线时执行CRUD操作,并且我很难找到一种方法来实现这一点。

这是从firestore中检索数据并调用以创建缓存文件时的代码。

代码语言:javascript
复制
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)
    }

}

下面是创建缓存文件的方式:

代码语言:javascript
复制
@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

代码语言:javascript
复制
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“中,而不是覆盖它?以及如何编辑/删除存储在缓存文件中的列表中的内容?

EN

回答 1

Stack Overflow用户

发布于 2020-12-30 02:33:12

Firestore自动处理离线读写。请参阅handling read and writes while offline上的文档。

如果你不想依赖它,你必须在你自己的持久层中复制它。这包括(但可能不限于):

  1. 保留暂挂写入的列表,当连接为restored.
  2. Return最新数据以进行本地读取时,您将该列表发送到服务器端数据库,这意味着您将本地高速缓存中的数据与该数据的任何暂挂写入合并。
  3. 解决连接恢复时可能发生的任何冲突。因此,您要么在此时更新本地缓存,要么不更新,并从挂起写入列表中删除该项目。

根据您的场景,可能会有更多的步骤。如果你被某个特定的步骤卡住了,我建议你回复一个新的问题,并提供关于该步骤的具体细节。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65493116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档