Search code examples
javanullpointerexceptionnulljoptionpane

Null pointer exception when JOptionPane.showMessageDialog is cancelled


Despite efforts reading on how Null Pointer Exceptions are generated, I literally have no clue how this error is generating itself within my code.

I don't think this affects my code directly, as I could just catch the exception, but before I do that, I'd still like to learn more about the error.

Part of my code where the error is generating, I am opening a new Input dialog and waiting for the user's input. If the user cancels the input dialog, it's just meant to close the dialog, in which it does. However, it's giving me an error every time I cancel.

Here's the code:

String newInput = JOptionPane.showInputDialog(null, "Your current holdings are: "
        + cable.getHoldings(), "Edit Holdings", JOptionPane.CANCEL_OPTION);

if (newInput.isEmpty())
{
    //Error generated here
    JOptionPane.showMessageDialog(null, "Please enter in a number!");

}

else
{...}

The message dialog is only triggered if the user presses the 'OK' button on the input dialog. Otherwise, if a user cancels or exits the input dialog, a null pointer exception error is generated.

Does anyone mind helping me and letting me know why this is happening?

Thank you.


Solution

  • From docs

    Returns: user's input, or null meaning the user canceled the input

    so it retruns null if user cancel the dialog

    From showInputDialog source code

     if (value == UNINITIALIZED_VALUE) {
                 return null;
             }
    

    Solutions : put a nullity check before doing anything

    if (newInput==null || newInput.isEmpty())
    

    you don't need newInput.isEmpty() because it checks the length of a string so even user enters a space length will be 1 or length will be null in case of cancelled input so nullity check is only enough for checking some input.

    Improvement : you can use regex to validate your input, is digit or not ,like this

    if (newInput==null || !newInput.matches("\\d+"))
    {
        JOptionPane.showMessageDialog(null, "Please enter in a number!");
    
    }
    

    \\d+ check the input should contain at-least one or more integer digits.