将对象缓存到android(kotlin)中的文件

Posted

技术标签:

【中文标题】将对象缓存到android(kotlin)中的文件【英文标题】:Caching an object to a file in android (kotlin) 【发布时间】:2021-04-06 03:21:39 【问题描述】:

我目前正在从 firestore 检索数据并将检索到的数据保存到列表中,该列表用于在内部存储中创建缓存文件。当应用程序启动时,我会检查网络,如果没有网络,我会使用缓存中的数据来填充 recyclerview。这工作正常,但是我想在离线时执行 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”添加一些东西而不是覆盖它?以及如何编辑/删除存储在缓存文件中的列表中的某些内容?

【问题讨论】:

Firestore 自动处理离线行为。见firebase.google.com/docs/firestore/manage-data/enable-offline 是的,我知道。出于学习目的,我仍然想这样做。 好的。我在下面写了一个快速概述。除此之外,很难给你一个具体的答案,因为这个问题要么相当广泛,要么你有一个更具体的问题,我从帖子中不清楚。 【参考方案1】:

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

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

    保留挂起的写入列表,在连接恢复时发送到服务器端数据库。 为本地读取返回最新数据,这意味着您将本地缓存中的数据与相同数据的任何待处理写入合并。 解决恢复连接时可能发生的任何冲突。因此,此时您要么更新本地缓存,要么不更新,然后从挂起的写入列表中删除该项目。

可能还有更多步骤,具体取决于您的方案。如果您在某个特定步骤上遇到困难,我建议您回复一个新问题,并提供有关该步骤的具体细节。

【讨论】:

以上是关于将对象缓存到android(kotlin)中的文件的主要内容,如果未能解决你的问题,请参考以下文章

将 Kotlin 运行时库添加到 android 中的 aar

android kotlin缓存目录等于null?

Kotlin Android,从 HTTP 请求解析 Json

如何使用 Kotlin 在 android 中的 BottomNavigationView 上设置 OnNavigationItemListener?

使用 kotlin for android app 将 pdf 文件上传到 firebase 存储

Android 中的缓存