Question

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?

Was it helpful?

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();

OTHER TIPS

You are on a different platform, you cannot use Java optionPane. You need to use either Toast or Dialog Look at these links http://www.codeproject.com/Articles/107341/Using-Alerts-in-Android

http://developer.android.com/guide/topics/ui/notifiers/toasts.html

Use Toast like:

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();
    Toast.makeText(YourActivity.this,"YOUR MESSAGE",Toast.LENGTH_SHORT).show();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top