java – Position from adapters onBindViewHolder doesn't get show in toast-ThrowExceptions

Exception or error:

So I’m trying to print the position from onBindViewHolder, but my toast is blank.

public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
....
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ....
                intent.putExtra("position", position);
                context.startActivity(intent);
            }
        });
}

all this is in the end being printed in a toast in my MainActivity

String pos = getIntent().getStringExtra("position");
Toast.makeText(this, pos, Toast.LENGTH_SHORT).show();

I can’t seem to find the issue, on how to get the position value of the onBindViewHolder function.

How to solve:

Change this way your code

 String pos = getIntent().getIntExtra("position",0).toString();
Toast.makeText(this, pos, Toast.LENGTH_SHORT).show();

###

Any other child view of this same parent could be accessible from v.

I have EditText & Button in a row, when I click on button below code will give you value of EditText to pass to another Activity. By this way I can send id of the row.

ConstraintLayout layout = (ConstraintLayout)v.getParent();
intent.putExtra("editTextValue", ((EditText)layout.getChildAt(0)).getText());
            context.startActivity(intent);

###

Simply change position to string value by one line of code –

intent.putExtra("position", position+"");

Leave a Reply

Your email address will not be published. Required fields are marked *