将变量(位置)从onBindViewHolder传递到ViewHolder类

时间:2018-04-05 14:49:30

标签: android firebase android-recyclerview recycler-adapter

我正在尝试将maxDrawdown的字符串(userID)传递给我的onBindViewHolder类。这背后的原因是我需要职位来分配正确的postID。此postID在ViewHolder中用作设置Firebase ViewHolder的参考。但是,在运行应用程序时,我在postID上获得valueEventListener。这是由于同步吗?在postID之前调用NullPointerException是否已设置?

valueEventListener

2 个答案:

答案 0 :(得分:0)

是的,你在PostViewHolder的构造函数中调用它,onCreateViewHolder之前由onBindViewHolder方法调用。

答案 1 :(得分:0)

ViewHolder类中创建一个方法,并从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);
}

}