java - Firebase Firestore 分布式计数器文档代码崩溃
问题描述
我正在按照文档在 Firebase Firestore 中创建分布式计数器,但是,他们提供的代码出现错误。
// counters/${ID}
public class Counter {
int numShards;
public Counter(int numShards) {
this.numShards = numShards;
}
}
// counters/${ID}/shards/${NUM}
public class Shard {
int count;
public Shard(int count) {
this.count = count;
}
}
运行他们定义的 createCounter 方法时
public Task<Void> createCounter(final DocumentReference ref, final int numShards) {
// Initialize the counter document, then initialize each shard.
return ref.set(new Counter(numShards))
.continueWithTask(new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(@NonNull Task<Void> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
List<Task<Void>> tasks = new ArrayList<>();
// Initialize each shard with count=0
for (int i = 0; i < numShards; i++) {
Task<Void> makeShard = ref.collection("shards")
.document(String.valueOf(i))
.set(new Shard(0));
tasks.add(makeShard);
}
return Tasks.whenAll(tasks);
}
});
}
我只是得到一个运行时异常
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.enterprises.optaku.bvalyan.gametalk, PID: 8471
java.lang.RuntimeException: No properties to serialize found on class com.enterprises.optaku.bvalyan.gametalk.TopicVotingFragment$Counter
at com.google.firebase.firestore.g.zzg$zza.<init>(SourceFile:643)
at com.google.firebase.firestore.g.zzg.zza(SourceFile:331)
at com.google.firebase.firestore.g.zzg.zzb(SourceFile:152)
at com.google.firebase.firestore.g.zzg.zza(SourceFile:1085)
at com.google.firebase.firestore.UserDataConverter.convertPOJO(SourceFile:427)
at com.google.firebase.firestore.DocumentReference.set(SourceFile:165)
at com.enterprises.optaku.bvalyan.gametalk.TopicVotingFragment.createCounter(TopicVotingFragment.java:217)
at com.enterprises.optaku.bvalyan.gametalk.TopicVotingFragment.lambda$null$5$TopicVotingFragment(TopicVotingFragment.java:180)
即使当我序列化类时,当我去增加计数器时,我仍然会在他们的代码中遇到异常
Shard shard = transaction.get(shardRef).toObject(Shard.class);
编译器抱怨 Shard 类中没有无参数构造函数。
我在这里不知所措,因为这是我能找到的唯一文档。有没有人成功地实现了这一点并且知道我在这里可能会错过什么?
解决方案
正如错误消息所说,您的 Shard 类没有无参数构造函数。JavaBean 类型类必须有一个无参数的构造函数,以便它被无法完全理解其他构造函数做什么的代码实例化。因此,您应该在代码中添加一个无参数构造函数:
public class Shard {
int count;
public Shard() {} // this constructor has no arguments
public Shard(int count) {
this.count = count;
}
}
如果没有该构造函数,Firestore SDK 就无法以可预测的方式创建Shard
.
推荐阅读
- python - 如何在带有 if 的辅助函数中使用 isdigit() 方法
- kubernetes-helm - 从另一个目录升级 helm chart
- c# - 通过套接字发送图像,几乎所有字节都替换为“?”
- apache-camel - 如何使用端点 DSL 配置 HTTP 端点以使用 https 而不是 http?
- php - PHP:检查动态添加的文件上传是否为空
- css - 编译 SCSS 关于使用 '/' 进行除法的警告
- facebook - 如何删除未批准的网址并重新提交 Facebook 即时文章中的文章
- reactjs - React - 如果路径不存在,则重定向到默认路径
- java - Spring Boot 应用程序正在将空值插入到我的 mysql 表中
- java - 如何在 Java(Dropwizard 框架)中进行异步 API 调用以更新 Couchbase 记录?