Search code examples
androidandroid-layoutprojects-and-solutions

AlertDialog.Builder in android program showing error


I was building a login page for an application in android. but while testing it gives the error at AlertDialog.Builder, saying that it has been not defined. I have used it in another apps and was working perfectly. Thanks in advance. This is the code:

package project.login;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    Button launch = (Button)findViewById(R.id.login_button);

    launch.setOnClickListener( new OnClickListener ()
    {
        public void onClick(View view)
        {   EditText usernameEditText = (EditText) findViewById(R.id.username);
            EditText passwordEditText = (EditText) findViewById(R.id.password);

            String sUsername = usernameEditText.getText().toString();
            String sPassword = passwordEditText.getText().toString();

            if(usernameEditText == null || passwordEditText == null) {
                new AlertDialog.Builder(this)
                .setTitle("Error")
                .setMessage("You can't let the fields empty")
                .show();
                } 
            }

        }
    );
  }

} 

Solution

  • The problem is that your this inside of your OnClickListener needs to be qualified. Try using

    new AlertDialog.Builder(LoginActivity.this)
                .setTitle("Error")
                .setMessage("You can't let the fields empty")
                .show();