Passing variable(position) from onBindViewHolder to ViewHolder class

蓝咒 提交于 2020-01-24 00:56:26

问题


I am trying to pass a String (userID) from the onBindViewHolder to my ViewHolder class. The reason behind this is that I need the position to allocate the correct postID. This postID is used in the ViewHolder as a reference to set up a Firebase valueEventListener. However, when running the app I get a NullPointerException on the postID. Is this due to synchronization? Is the valueEventListener called before postID is set?

public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    final PostViewHolder holder1 = (PostViewHolder) holder;
    holder1.postID = getPostId(position)

    //...
}

//...

public class PostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    private DatabaseReference mNoOfLikesRef;
    public String postID;
    //...

    public PostViewHolder(View itemView, postClickListener listener){
        super(itemView);

        //This line causes the NullPointerException on postID
        mNoOfLikesRef = FirebaseDatabase.getInstance().getReference().child("likes").child(postID);
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                //...
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }

        };
        mNoOfLikesRef.addListenerForSingleValueEvent(valueEventListener);

    }

回答1:


Yes, you're calling it in PostViewHolder's constructor which is invoked by onCreateViewHolder method before onBindViewHolder.




回答2:


create a method inside ViewHolder class and call it from onBindViewHolder

public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    final PostViewHolder holder1 = (PostViewHolder) holder;
    holder1.doYourTask(getPostId(position));

    //...
}

public class PostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

//...

public void doYourTask(String postID){
    DatabaseReference mNoOfLikesRef = FirebaseDatabase.getInstance().getReference().child("likes").child(postID);
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //...
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }

    };
    mNoOfLikesRef.addListenerForSingleValueEvent(valueEventListener);
}

}



来源:https://stackoverflow.com/questions/49675314/passing-variableposition-from-onbindviewholder-to-viewholder-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!