How to add message box with 'OK' button?
The code compiles ok for me. May be you have forgotten to add the import:
import android.app.AlertDialog;
Anyway, you have a good tutorial here.
I think there may be problem that you haven't added click listener for ok positive button.
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
Since in your situation you only want to notify the user with a short and simple message, a Toast
would make for a better user experience.
Toast.makeText(getApplicationContext(), "Data saved", Toast.LENGTH_LONG).show();
Update: A Snackbar is recommended now instead of a Toast for Material Design apps.
If you have a more lengthy message that you want to give the reader time to read and understand, then you should use a DialogFragment
. (The documentation currently recommends wrapping your AlertDialog
in a fragment rather than calling it directly.)
Make a class that extends DialogFragment
:
public class MyDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("App Title");
builder.setMessage("This is an alert with no consequence");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// You don't have to do anything here if you just
// want it dismissed when clicked
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Then call it when you need it in your activity:
DialogFragment dialog = new MyDialogFragment();
dialog.show(getSupportFragmentManager(), "MyDialogFragmentTag");
See also
- Android Alert Dialog with one, two, and three buttons