santafebound santafebound - 14 days ago 11
Android Question

AlertDialog.Builder helper class cannot resolve constructor

I've built a helper class to store various AlertDialog types. I thought it would be helpful so that I could call them anywhere in my code. Unfortunately I get an error below at

new AlertDialog.Builder()
. It says
Cannot resolve constructor `Builder()
. How can I get this to work?

public class AlertDialogHelper {

public void showAboutDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder();
builder.setTitle(R.string.about);
builder.setMessage("A weather app made by Martin Erlic")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Ok
}
});
AlertDialog alert = builder.create();
alert.show();
}

}


In my activity:

private void showAboutAlertDialog() {
AlertDialogHelper alertDialogHelper = new AlertDialogHelper();
alertDialogHelper.showAboutDialog();
}

Answer

You should pass a Context in the constructor like this:

AlertDialog.Builder builder = new AlertDialog.Builder(context);

From your activity:

alertDialogHelper.showAboutDialog(this);

now:

public void showAboutDialog(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        ....
Comments