Parse.com:保存时获取唯一号码

时间:2015-12-22 09:27:36

标签: java android parse-platform synchronization

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

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

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

保存时如何设置号码?当我保存Point并给它一个唯一的号码然后在我的应用程序中使用

时,我正考虑在云中添加WebHook
newPoint.saveEventually(new SaveCallback() {            
        public void done(ParseException e) {
            //query for the number
        }
    });

从云中查询点以获取保存后的数字。但这对于这样一个简单的要求来说似乎太复杂了。而且我不确定保存时是否始终触发SaveCallback()

1 个答案:

答案 0 :(得分:1)

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

以下是云代码的样子:

// 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()一起使用时要记住的一点重要信息是:

  

只有在操作完成后才会调用回调   当前的应用生命周期。如果该应用已关闭,则无法进行回调   即使保存最终完成,也会调用。

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();
});