I'm trying to show a toast when I click this button. But the code is not working

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    Button btn = (Button) findViewById(R.id.button1);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            EditText text = (EditText)findViewById(R.id.editText1);
            EditText text1 = (EditText)findViewById(R.id.editText2);
            String userid = text.getText().toString();
            String pass = text1.getText().toString();
        Toast.makeText(getBaseContext(),"Entered"+userid+"and password entered is"+pass,Toast.LENGTH_SHORT).show();
        }

    });

}

The code runs successfully, but nothing happens when the button is clicked. When I focus on the line in eclipse, it says the following

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

Please tell me what I need to do to make it work.

+5
source share
3 answers

You should pass the current Context as the first parameter (instead getBaseContext()). It is, in your case MainActivity.this.

Toast.makeText(MainActivity.this,"Entered"+userid+"and password entered is"+pass,Toast.LENGTH_SHORT).show();
+16
source

, getBaseContext() . , , - . Toast View.getContext() ( ) this.

+2
Toast.makeText(getApplicationContext(),"Entered"+userid+"and password entered is"+pass,Toast.LENGTH_SHORT).show();

OR

Toast.makeText(MainActivity.this,"Entered"+userid+"and password entered is"+pass,Toast.LENGTH_SHORT).show();

Method Syntax

public static Toast makeText (Context context, CharSequence text, int duration);

Context of use. Usually your Application or Activity object.

0
source

All Articles