Reputation: 1621
I have created a dialog which can be called from anywhere by supplying a title and message as follows:
public void alertbox(String title, String mymessage)
{ new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(mymessage)
.setNeutralButton(android.R.string.cancel,
new DialogInterface.OnClickListener()
{ public void onClick(DialogInterface dialog, int whichButton) {}
})
.show();
}
But I get a lockup when I try to dismiss the dialog from another method:
private void doCheck() {
alertbox("status", getString(R.string.checking_license));
mChecker.checkAccess(mLicenseCheckerCallback);
alertbox.dismiss();
}
It is the alertbox.dismiss(); statement that causes the crash. Any ideas how to properly do this?
Upvotes: 2
Views: 5428
Reputation: 2648
I came across this issue also and wanted to share my solution for anyone who chooses not to use the above method.
Firstly I defined my AlertDialog along with the class variables:
private AlertDialog alertbox;
Then I initiate the AlertDialog wherever it is required:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("title");
builder.setMessage("message");
alertbox = builder.create();
alertbox.show();
Finally, due to orginally defining the AlertDialog as an instance variable, I can close the AlertDialog through any methods within the class.
private void dismissAlert()
{
alertbox.dismiss()
}
Upvotes: 5
Reputation: 44919
It could be as simple as calling runOnUiThread
:
runOnUiThread(new Runnable() {
@Override
public void run() {
alertbox.dismiss();
}
});
if you are on the wrong thread. Although with your additional details, the problem is more simple. To give away the punchline:
public AlertDialog alertbox(String title, String mymessage) {
return new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(mymessage)
.setNeutralButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
})
.show();
}
and:
private void doCheck() {
AlertDialog alert = alertbox("status", getString(R.string.checking_license));
mChecker.checkAccess(mLicenseCheckerCallback);
alert.dismiss();
}
Although you probably don't want to both show and dismiss the dialog in the same method. Do you see how the above code is at least saving a reference to the dialog so that you can dismiss it later?
Upvotes: 4
Reputation: 814
I would have alertBox return the dialog like so
public AlertDialog alertbox(String title, String mymessage)
Then wherever you call it you can keep reference to the returned dialog and dismiss it as needed.
Upvotes: 1