Search code examples
androidmessagedialog

Showing a message dialog in Android


Today I've started to build my first android app, I'm used to work with Java but there are something that I don't know how to do in my android app. It's a simple calculator, and I'm trying to show a message dialog if the user inputs an invalid number.

Here's my code:

public void calculate(View v) {
    EditText theNumber = (EditText) findViewById(R.id.number);
    int num;
    try {
        num = Integer.parseInt(theNumber.getText().toString());
    } catch (NumberFormatException e) {
        //missing code here
    }
}

In Java SE I'd just do this:

public void calculate(View v) {
    EditText theNumber = (EditText) findViewById(R.id.number);
    int num;
    try {
        num = Integer.parseInt(theNumber.getText().toString());
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog("Invalid input");
    }
}

How can I do that in android?


Solution

  • Master of Puppets: Yes, you could use Toast but if you want an actual popup dialog use AlertDialog:

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    
    builder.setTitle("Your Title");
    
    builder.setMessage("Some message...")
           .setCancelable(false)
           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                      // TODO: handle the OK
                    }
              })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                      dialog.cancel();
                    }
            });
    
    AlertDialog alertDialog = builder.create();
    alertDialog.show();