我使用 Parse.com我的 Android 应用中的云服务可在设备之间同步数据。
我主要离线使用该应用程序并使用本地数据存储。
有一个名为 Point
的类,它有一个唯一的数字作为我要显示的标识符。因此,当离线工作时,我想创建一个点作为草稿(草稿文本作为数字),而在同步时,我希望它获得在所有设备上唯一的真实数字。
保存时如何设置数字?我正在考虑在保存点时在云中添加一个 WebHook 并为其提供唯一编号,然后在我的应用程序中使用
newPoint.saveEventually(new SaveCallback() {
public void done(ParseException e) {
//query for the number
}
});
保存后从云端查询点数。但是对于这样一个简单的要求来说,这似乎有点太复杂了。而且我不确定 SaveCallback()
在保存时是否总是被触发。
最佳答案
我建议使用 afterSave trigger在 Point
类上设置新创建对象时的唯一标识符。然后,正如您所提到的,您需要在显示之前获取该值。
云代码如下所示:
// 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);
}
});
关于将 saveEventually
与 SaveCallback()
一起使用的重要信息是:
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.
如果唯一标识符应立即显示在应用程序中,或者如果需要一致地处理回调,最好使用 saveInBackground
而不是 saveEventually
。
另一种选择是根据网络可用性和/或离线设置动态更改回调。例如,如果在手机信号或wifi不可用时随时使用离线模式,则network reachability可用于检查网络,然后根据需要使用 saveInBackground
或 saveEventually
。
更新
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/