我正在尝试使用Firebase Firestore在Android上创建Property Rental应用程序 . 现在,我正在尝试实现一种方法来删除Firestore中我的集合中的特定文档(属性) . 我认为它是通过引用该特定文档的自动生成的ID,但我根本无法解决它 .
这是删除功能应该如何工作:
-
用户点击RecyclerView中的属性项
-
显示property的完整 Profiles
-
用户点击右上角的删除按钮,然后从Firestore database删除该属性
这是我的代码,我被困在:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
// The delete button
case R.id.action_delete_btn:
// Do this when user clicks on delete button
Toast.makeText(PropertyProfile.this, "You tried to delete this property", Toast.LENGTH_LONG).show();
deleteItem(item.getOrder());
return super.onOptionsItemSelected(item);
default:
return false;
}
}
// Here's my problem
private void deleteItem(int index) {
firebaseFirestore.collection("Posts")
.document("[DOCUMENT ID RIGHT HERE!]")
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(PropertyProfile.this, "You successfully deleted this property", Toast.LENGTH_LONG).show();
}
});
}
1 回答
要使用您要查找的文档ID,首先需要将其存储在变量中 . 将文档添加到数据库并且在不传递参数的情况下使用
document()
方法调用时,将生成唯一的ID . 要获取该ID,您应该使用以下代码:其中
postsRef
是Posts
集合的CollectionReference
对象,yourModelObject
是Post
类的对象 . 我还建议您将该ID存储为Post文档的属性 .一旦你有了这个id,就可以在你的refence中使用这样的: