Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error due to invalid combination of Toast and OnClickListener

Tags:

android

toast

I'm trying to use Toast inside OnCLickListener. My code triggers the following error:

The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (new View.OnClickListener(){}, String, int) 

This is my code:

    Button register = (Button) findViewById(R.id.register);     register.setOnClickListener(new View.OnClickListener() {         public void onClick(View arg0) {             EditText name = (EditText)findViewById(R.id.name);             String Lname = name.getText().toString();              Toast.makeText(this, Lname, Toast.LENGTH_SHORT).show();            }     }); 
like image 954
Harsha M V Avatar asked Dec 25 '10 20:12

Harsha M V


2 Answers

As The Kenny said, this is refering to the View.OnClickListener instead of your Activity. Change this, to MyActivity.this.

For example,

public class MyActivity extends Activity { // ... other code here Toast.makeText(MyActivity.this, Lname, Toast.LENGTH_SHORT).show(); 
like image 71
Computerish Avatar answered Oct 04 '22 22:10

Computerish


In this case, this refers to the instance of the anonymous subclass of View.OnClickListener. You have to refer to the this of the class where you create the anonymous class.

like image 32
jsadfeew Avatar answered Oct 04 '22 23:10

jsadfeew