从onBindViewHolder传递变量(位置)到ViewHolder类 [英] Passing variable(position) from onBindViewHolder to ViewHolder class

查看:707
本文介绍了从onBindViewHolder传递变量(位置)到ViewHolder类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将字符串(userID)从onBindViewHolder传递给我的ViewHolder类.这背后的原因是我需要分配正确的postID的职位.该postID在ViewHolder中用作设置Firebase valueEventListener的参考.但是,当运行该应用程序时,我在postID上得到了NullPointerException.这是由于同步造成的吗?在设置postID之前会调用valueEventListener吗?

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);

    }

推荐答案

ViewHolder类中创建一个方法,然后从onBindViewHolder

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);
}

}

这篇关于从onBindViewHolder传递变量(位置)到ViewHolder类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆