[英]How do I allow users to delete their post from Firebase?
我設置了一個回收視圖,其中填充了Firebase中用戶的帖子。 我想實現一個功能,允許用戶刪除自己的帖子(類似於Facebook或Instagram)。 到目前為止,我已經編寫了一些允許刪除帖子的代碼,但是任何用戶都有權刪除它。
//This is how my database is set up
Post
-LlISwmjd0pBXzkNHJGW (random push id)
desc: "Used textbook"
id: "Zk32WqxcCHbR1op6j9inFudFJF23"
image: "image link"
name: "user name"
profileimage: "profile image"
//This method allows a post to be removed
//Creates popup and allows user to delete from RecycleView
public void openOptionMenu(View v, final int position) {
PopupMenu popup = new PopupMenu(v.getContext(), v);
popup.getMenuInflater().inflate(R.menu.options_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
Toast.makeText(getApplicationContext(), "Edit clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu2:
FirebaseDatabase.getInstance().getReference().child("Post").child(randomPostKeyId).removeValue();
postList.remove(position);
adapter.notifyDataSetChanged();
return true;
default:
//default intent
return true;
}
}
});
popup.show();
}
我不確定我是否正確理解了您的問題。 根據我的理解,如果該帖子是由用戶交互創建的,則您希望顯示該帖子的delete選項。
如果是這樣,請在“ openOptionMenu”方法中添加檢查以查看post.name == currentUser.name。 如果是,請繼續您現在所做的一切。 否則會為新的選項菜單充氣,而刪除選項不存在。
您可以設置Firebase安全性規則,以便只有所有者才能修改/刪除帖子。 假設每個帖子都有一個屬性,其中包含創建該帖子的用戶的用戶ID,如果鍵的名稱為ownerId
則其外觀如下所示:
{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data
"rules": {
"Post": {
"${postId}": {
".read": true,
// or ".read": "auth.uid != null" for only authenticated users
".write": "root.child('Post').child(postId).child('ownerId').val() == auth.uid"
}
}
}
}
查看https://firebase.google.com/docs/rules以獲取完整的文檔說明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.