【发布时间】:2020-03-17 19:07:22
【问题描述】:
所以,我正在开发一个 Android 应用程序,我尝试通过按一个按钮将字段的值增加 1。基本上,我有一组用户,每个用户都有一个帖子的子集合,每个帖子都有一个名为“申请人”的数字字段,我用它来计算有多少人申请了一份工作。
问题是我找不到查询确切文档字段的方法,因为我无法以编程方式获取文档 ID。我一直在尝试通过搜索其标题来识别该帖子,但没有运气。当我运行代码时,它不会抛出任何错误,应用程序不会崩溃,但我的数据库中仍然没有任何变化。
这是我的数据库结构:
public void executeTransaction(int position){
db.runTransaction(new Transaction.Function<Void>() {
@Nullable
@Override
public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException {
db.collectionGroup("posts").whereEqualTo("title", list.get(position).getTheTitle()).get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
DocumentReference postRef = usersRef.document("posts");
DocumentSnapshot postSnapshot = null;
try {
postSnapshot = transaction.get(postRef);
} catch (FirebaseFirestoreException e) {
e.printStackTrace();
}
long newApplicants = postSnapshot.getLong("applicants") + 1;
transaction.update(postRef, "applicants", newApplicants);
}
});
return null;
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(context, "You have applied to this job!", Toast.LENGTH_SHORT).show();
}
});
这是在您点击“应用”按钮时运行的方法。参数“位置”只是帖子存储在本地ArrayList<Post> list 中的位置。
我怎样才能简单地增加帖子的applicants 值?
【问题讨论】:
-
你能以编程方式获得
userId吗? -
@GauravMall 是的,我的 userId 和发帖者的 userId 也是
-
为什么不能以编程方式获取帖子的ID?您组织它的方式应该能够为您提供职位。您能告诉我们如何保存帖子吗?
-
我找不到任何方法来获取它的 ID。我有一个 ArrayList
列表,我保存从 Firestore 读取的帖子,这样:``` for (DocumentSnapshot documentSnapshot : documentSnapshots.getDocuments()) { Post post = new Post(); post.setTitle(documentSnapshot.getString("title")); post.setApplicants(documentSnapshot.getLong("applicants")); ... list.add(post); } notifyDataSetChanged(); ``` -
现在检查我的答案,它应该可以工作。
标签: android firebase google-cloud-firestore