Search code examples
javanullpointerexceptionjoptionpane

java: JOptionPane.showInputDialog null pointer exception


    String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:");

This throws a null pointer error if the user x's out of the optionpane

Firstly, why can't response hold a null value?

secondly, how do i handle this?

full code:

    String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:").trim() + ".xml"; 
    if(response != null){
        File newData = new File("src\\golfdatabase\\Databases\\" + response);
        try {
            newData.createNewFile();
            databaseComboBox.addItem(response);
        } catch (IOException ex) {
            Logger.getLogger(GolfDriver.class.getName()).log(Level.SEVERE, null, ex);
        }
        databaseComboBox.setSelectedItem(response);
        disableButtonsNullList(false);
    }

Solution

  • You have to check the return value for null and then invoke the method trim

    String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:");
    if(response!=null)
    response = response.trim()+".xml";