0

I am trying to call an alert dialog from another class but this is not letting me set it to static. It shows as only final is permitted and that means it cannot call it from the other class. I'm not sure if I am doing it correctly or if it is even possible. I have the alert dialog in class 2:

static final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
            alertDialog = new AlertDialog.Builder(this).create();

        alertbox.setTitle("Hello");
        alertbox.setMessage("Press Continue or Cancel");
        alertbox.setPositiveButton("CONTINUE",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {


                    }
                });

        alertbox.setNegativeButton("CANCEL",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

        alertDialog.setIcon(R.drawable.icon);

This then gets called in class1:

QuizValidation.alertbox.show();

Which also cannot be resolved.

I can probably sort that out if I could set the alertbox in class 2 to static.

Would appreciate any advice.

Thanks

Raj
  • 693
  • 4
  • 17
  • 29

3 Answers3

2

Create a Constructor, where you can get Activity. Like this -

Activity activity;
public YourClass (Activity activity){
         this.activity = activity;
}

Now, use this activity as argument -

AlertDialog.Builder adb=new AlertDialog.Builder(activity);

Because dialog can't be shown using just a context. You need to provide an Activity for that.

Darpan
  • 5,623
  • 3
  • 48
  • 80
2

Its a better idea to define all your dialogs in a base class , lets call it ... well BaseActivity

Class BaseActivity extends Activity{

int DIALOG_X = 1;
int DIALOG_Y = 2;
int DIALOG_Z = 3;
// More Dialog identifiers 

ProgressDialog progressDialog;
AlertDialog alertDialog;
//More dialog objects if you need

protected Dialog onCreateDialog(int id) {
    Dialog dialog;
    switch(id) {
    case DIALOG_X:
        // do the work to define the X Dialog
        break;
    case DIALOG_Y:
        // do the work to define the Y Dialog
        break;
    default:
        dialog = null;
    }
    return dialog;
}
}

Then in another class extend BaseActivity and call

showDialog(DIALOG_X); 

when you need to show Dialog_X

Ravi Vyas
  • 12,212
  • 6
  • 31
  • 47
  • I cant extend the class from the main class. This already uses a bunch of classes and shows errors if I extend it. It also uses a global application. Thanks for your help, I'll just leave it in there for now. – Raj Mar 03 '11 at 17:39
  • I always make base class for my project, but never thought of it. Thank you – Rohit May 23 '14 at 06:36
0

You can also simply extend AlertDialog, and make your own and reuse.

oriharel
  • 10,418
  • 14
  • 48
  • 57