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);
setContent开发者_如何学GoView(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();
}
}
}
);
}
}
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();
Don't forget to import android.app.AlertDialog first.
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton(Dialog.BUTTON_POSITIVE,"OK",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
精彩评论