Yoh Hendry
Yoh Hendry

Reputation: 427

creating alertdialog inside a non activity class

i have a class that implements view.onclicklistener. how do i create an alert dialog from this class which is not an activity class.

i kept on getting this error.

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

this is my code

class LoginView implements View.OnClickListener {
public void onClick(final View v) {
    new AlertDialog.Builder(v.getContext())
                            .setTitle("Delete entry")
                            .setMessage("Are you sure you want to delete this entry?")
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    // continue with delete
                                }
                            })
                            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    // do nothing
                                }
                            })
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .show();

Upvotes: 0

Views: 660

Answers (2)

Zied R.
Zied R.

Reputation: 4964

try this method in your class:

 public static void showAlert(Activity activity) {


    new AlertDialog.Builder(activity)
                        .setTitle("Delete entry")
                        .setMessage("Are you sure you want to delete this entry?")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // continue with delete
                            }
                        })
                        .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // do nothing
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
}

Upvotes: 0

Murtaza Khursheed Hussain
Murtaza Khursheed Hussain

Reputation: 15336

Do it like this

 private Handler mHandler = new Handler(Looper.getMainLooper());

 @Override
    public void run() {
       // ...
       mHandler.post(new Runnable() {
          public void run() {
              // Create your AlertDialog Here...
          }
       });
       // ...
     }

Upvotes: 2

Related Questions