Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am trying to display a toast when this button is pressed. But the code is not working

Tags:

android

toast

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 executes successfully, but nothing happens when the button is pressed. 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 do i require to do to make it work

like image 434
tmj Avatar asked Mar 07 '13 17:03

tmj


People also ask

Why is toast not displaying?

Make sure not to forget to call show() after the makeText. Check for the Context , if its the right one. The most important one , make sure your Android Notifications are on for your app, else the Toast will not be shown.


2 Answers

You have to pass the current Context as first parameter (instead of getBaseContext()). This, in your case, is MainActivity.this.

Toast.makeText(MainActivity.this,"Entered"+userid+"and password entered is"+pass,Toast.LENGTH_SHORT).show();
like image 161
poitroae Avatar answered Nov 15 '22 04:11

poitroae


It is because the getBaseContext() at that point in the code is referencing the click listener. What you want to reference is your activity. You should change the reference of your Context in the Toast message to be View.getContext()(if working on the context from within a subview) or this.

like image 45
Jay Snayder Avatar answered Nov 15 '22 04:11

Jay Snayder