java - 解析.com : Get unique number when saving

标签 java android parse-platform synchronization

我使用 Parse.com我的 Android 应用中的云服务可在设备之间同步数据。

我主要离线使用该应用程序并使用本地数据存储。

有一个名为 Point 的类,它有一个唯一的数字作为我要显示的标识符。因此,当离线工作时,我想创建一个点作为草稿(草稿文本作为数字),而在同步时,我希望它获得在所有设备上唯一的真实数字。

保存时如何设置数字?我正在考虑在保存点时在云中添加一个 WebHook 并为其提供唯一编号,然后在我的应用程序中使用

newPoint.saveEventually(new SaveCallback() {            
        public void done(ParseException e) {
            //query for the number
        }
    });

保存后从云端查询点数。但是对于这样一个简单的要求来说,这似乎有点太复杂了。而且我不确定 SaveCallback() 在保存时是否总是被触发。

最佳答案

我建议使用 afterSave triggerPoint 类上设置新创建对象时的唯一标识符。然后,正如您所提到的,您需要在显示之前获取该值。

云代码如下所示:

// Assign the Point a unique identifier on creation
Parse.Cloud.afterSave("Point", function(request) {

    // Check if the Point is new
    if (!(request.object.existed())) {

        // Get the unique identifier
        var uniqueIdentifier = ...

        // Set the unique identifier
        request.object.set('uniqueIdentifier', uniqueIdentifier);
    }
});

关于将 saveEventuallySaveCallback() 一起使用的重要信息是:

The callback will only be called if the operation completes within the current app lifecycle. If the app is closed, the callback can't be called, even if the save eventually is completed.

Source: Hector Ramos

如果唯一标识符应立即显示在应用程序中,或者如果需要一致地处理回调,最好使用 saveInBackground 而不是 saveEventually

另一种选择是根据网络可用性和/或离线设置动态更改回调。例如,如果在手机信号或wifi不可用时随时使用离线模式,则network reachability可用于检查网络,然后根据需要使用 saveInBackgroundsaveEventually

更新

OP 最终使用了这段代码:

Parse.Cloud.beforeSave("Point", function(request, response) {
    if (!(request.object.existed())) {
        var query = new Parse.Query("Point");
        query.addDescending("uniqueIdentifier");
        query.first({
            success: function(result) {             
                var maxId = result.get("uniqueIdentifier");             
                request.object.set("uniqueIdentifier", maxId + 1);                  
            },
            error: function() {                     
            }
        });            
    }
    response.success();
});

关于java - 解析.com : Get unique number when saving,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34412433/

相关文章:

java - 关于如何组合CDI beans的疑惑: SessionScoped and RequestScoped

Java 套接字重定向

java - java中字节数组到blob

android - Firebase 未向控制台报告崩溃

android - 具有复制功能的移动本地数据库(如 Couchbase lite、Parse.com 或 Claudant)可以替代 Web 服务层吗?

java - 从 Parse.com localDatastore 计算列(数字类型)的总和时遇到问题?

java - 从 Android 到服务器、PC 和 Android 设备的实时视频流

java - Android ListView 与 LinkedHashMap - 滚动时列表乱序

android - 获取调用我的应用程序的应用程序的包名称

java - 如何根据用户当前位置从解析中获取数据?