我使用FirebasaRecyclerAdapter来显示我在Firebase控制台中收到的帖子列表。我想获得每个帖子引用,以便能够删除它们。我已经可以获得网址:
public class PostAdapter extends FirebaseRecyclerAdapter<Post, PostViewHolder> {
private static final String TAG = Post.class.getSimpleName();
private Context context;
public PostAdapter(Class<Post> modelClass, int modelLayout, Class<PostViewHolder> viewHolderClass, DatabaseReference ref, Context context) {
super(modelClass, modelLayout, viewHolderClass, ref);
this.context = context;
}
@Override
protected void populateViewHolder(PostViewHolder viewHolder, Post model, int position) {
String postReference = this.getRef(position).toString();
viewHolder.bindPost(model, position, postReference);
}
@Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
}
我得到字符串postReference并将其发送到我的viewHolder。这个viewHolder是我用来在feed中显示帖子的那个。当用户点击帖子时,他可以将帖子详细信息放在另一个片段中(我发送postReference字符串:
Bundle bundle = new Bundle();
bundle.putSerializable("post", post);
bundle.putString("postReference", postReferece);
PostDetailFragment postDetailFragment = new PostDetailFragment();
postDetailFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = ((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_left_enter, R.anim.slide_left_exit, R.anim.slide_right_enter, R.anim.slide_right_exit);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.feed_container, postDetailFragment, "PostDetailFragment").commit();
在PostDetailFragment中,我想在点击删除按钮时删除该帖子,所以:
private View.OnClickListener deleteListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
String postReference = bundle.getString("postReference");
FirebaseDatabase.getInstance().getReference(postReference).removeValue();
((FeedActivity)context).getSupportFragmentManager().popBackStack();
}
};
我的问题是Firebase不接受我的&#34; postReference&#34;字符串,它说:
Invalid Firebase Database path: https://(myapp).firebaseio.com/users/(userkey)/posts/KIJ999. Firebase Database paths must not contain '.', '#', '$', '[', or ']'
对此有何想法?
答案 0 :(得分:0)
所以,我终于解决了这个问题。删除我的帖子时我需要使用帖子“路径”,这不是我到目前为止的URL。为了获得路径而不是URL,我做了:
@Override
protected void populateViewHolder(PostViewHolder viewHolder, Post model, int position) {
String postUrl = this.getRef(position).toString();
String postRoot = this.getRef(position).getRoot().toString();
String postReference = postUrl.replace(postRoot,"");
viewHolder.bindPost(model, position, postReference);
}
通过这样做,我删除了网址的“https://(myapp).firebaseio.com”部分(这是Firebase不接受的部分)并获取我要删除的帖子的路径。