Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
                } 
            }

        }
    );
  }

} 
like image 450
kiran Avatar asked Jun 04 '26 00:06

kiran


1 Answers

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();
like image 107
Justin Breitfeller Avatar answered Jun 05 '26 12:06

Justin Breitfeller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!