Sidhartha
Sidhartha

Reputation: 1090

How to retrieve recycler view item position in side a textwatcher?

I am getting NullPoniterExecption while retrieving the position inside CustomWatcher. My CustomTextWatcher class :

public static class CustomWatcher implements TextWatcher {

        private MyViewHolder hol;
        private EditText editText;

        public CustomWatcher(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            int position = (int)editText.getTag(R.id.id_ans_text);
            Log.d("SUB", position+" "+s);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }

    }

holder implementation class where I have set the watcher:

 public class MyViewHolder extends RecyclerView.ViewHolder{

        public EditText answer;
        private int position;

        public MyViewHolder(View view) {
            super(view);
            context = view.getContext();
            answer = (EditText) view.findViewById(R.id.id_ans_text);
            Log.d("ss",answer+"");
            CustomWatcher textWatcher = new CustomWatcher(answer);
            answer.addTextChangedListener(textWatcher);
}
}

Within onBindViewHolder :

 headerHolder.answer.setTag(R.id.id_ans_text, position);

Upvotes: 1

Views: 304

Answers (1)

Daniel Nugent
Daniel Nugent

Reputation: 43322

Since you have a separate instance of CustomWatcher for each item in the RecyclerView, you can just keep the position in an instance variable.

First, modify CustomWatcher so that it takes the position as a parameter of the constructor:

public static class CustomWatcher implements TextWatcher {

        private MyViewHolder hol;
        private EditText editText;
        private int position;

        public CustomWatcher(EditText editText, int pos) {
            this.editText = editText;
            this.position = pos;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //int position = (int)editText.getTag(R.id.id_ans_text);
            Log.d("SUB", position+" "+s);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
}

Then, create the CustomWatcher instance and call addTextChangedListener() in the onBindViewHolder() override:

@Override
public void onBindViewHolder(ViewHolder headerHolder, int position) {

    CustomWatcher textWatcher = new CustomWatcher(headerHolder.answer, position);
    headerHolder.answer.addTextChangedListener(textWatcher);

}

Upvotes: 1

Related Questions