Firestore脱机写入/添加不起作用

Ste*_*ton 5 android firebase google-cloud-firestore

我们可以让Firestore将记录下载到本地缓存,并可以读取这些记录.但是,我们无法更新记录,也无法添加新记录.

甚至尝试了一些相同的代码(https://github.com/firebase/quickstart-android),但似乎无法使离线写/插入工作 - 只读.

当我们将此函数调用为脱机时,它将被调用OnFailureListner并抛出异常

 @Override
public void onRating(Rating rating) {
    // In a transaction, add the new rating and update the aggregate totals
    addRating(mRestaurantRef, rating)
            .addOnSuccessListener(this, new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.d(TAG, "Rating added");

                    // Hide keyboard and scroll to top
                    hideKeyboard();
                    mRatingsRecycler.smoothScrollToPosition(0);
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "Add rating failed", e);

                    // Show failure message and hide keyboard
                    hideKeyboard();
                    Snackbar.make(findViewById(android.R.id.content), "Failed to add rating",
                            Snackbar.LENGTH_SHORT).show();
                }
            });
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*lli -1

您不能简单地离线写入数据,因为 Firestore 可以在您有 Internet 连接时获取数据并上传(这需要在后台运行任务)。Firestore 改进了其离线功能,但您始终可以选择创建自己的服务,以便在设备连接时上传它。

Android 允许您创建服务。来自developer.android.com

服务是在后台运行的组件,用于执行长时间运行的操作或为远程进程执行工作。服务不提供用户界面。例如,服务可能会在用户使用不同的应用程序时在后台播放音乐,或者可能会通过网络获取数据而不阻止用户与活动的交互。另一个组件(例如活动)可以启动该服务并让它运行或绑定到该服务以便与其交互。服务作为 Service 的子类实现。

因此,您可以创建一个Service不断等待互联网连接并仅调用该FirebaseFirestore对象来上传您想要的所有数据的对象。

这可能对你有帮助,这是有关服务的官方 Android 信息:https ://developer.android.com/guide/components/services.html