Boardy
Boardy

Reputation: 36205

Returning AlertDialog from Standard Java Class

I am currently working on an android project. I am trying to have an alert dialogue in a standard java class so that the code can be re-used throughout the app.

However, it is returning the alertdialog from the class back to the activity but when I attempt to show the alert dialog it displays the following error:

Unable to add window -- token null is not for an application

Below is the code that I have used to create the alert dialogue

public AlertDialog showAlertDialog(String message, Context context) 
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("hello")
            .setCancelable(false)
            .setPositiveButton("Yes", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
        AlertDialog alert = builder.create();
        return alert;
    }

Below is the code from the android activity where I am trying to show the alert dialog

Common cla = new Common();
AlertDialog alert = cla.showAlertDialog("Hello", getApplicationContext());
alert.show();

Common is the name of the class

Upvotes: 0

Views: 525

Answers (1)

kosa
kosa

Reputation: 66637

Please chage your AlerDialogCreation logic to AlertDialog.Builder builder = new AlertDialog.Builder(yourActivity.this);

Upvotes: 1

Related Questions