Android, How can I get text from TextView in OnClick

This is wrong

TextView tv2 = new TextView(this,(String)book.get(i),this);

You will need TextView to be final and the constructor should match any of the below

TextView(Context context)
TextView(Context context, AttributeSet attrs)
TextView(Context context, AttributeSet attrs, int defStyle)

It should be

final TextView tv2 = new TextView(this);

You are not using any of the above. Totally wrong

Then inside onClick

String str = tv2.getText().toString();  

Its declared final cause you access tv2 inside annonymous inner class.

You can also use the View v.

TextView tv = (TextView) v;
String str = tv.getText().toString();  

tv2.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
    Intent intent = new Intent(Contact.this,Discution.class);

            String str = tv2.getText().toString(); 


Just use: tv2 in place of this.

Leave a Comment