0

Here is the code throwing the error. In TextPad, I get a NullPointerException when I try to write the contents of the array to the text file. (It doesn't see anything in the array.) Note: it works perfectly in Netbeans. I only get this in Textpad. I have scoured Google and i have no idea why it is doing this.

    void enterContact(){
    // test contact
    contactName = nameField.getText();
    if (contactName == null || contactName.equals(""))
    {
        JOptionPane.showMessageDialog(null, "Please enter a name.");
        return;
    }

    //test age betweeen 0 and 120
    contactAge = ageField.getText();

    try{
        Integer.parseInt(contactAge);
    }
    catch(NumberFormatException e){
        JOptionPane.showMessageDialog(null, "Please enter a valid age.");
    }
    finally{
        if (Integer.parseInt(contactAge) <= 0 || Integer.parseInt(contactAge) >= 121){
            JOptionPane.showMessageDialog(null, "Please enter a valid age.");
            return;
         }
    }

    // test email
    contactEmail = emailField.getText();
    if ( contactEmail == null || contactEmail.equals(""))
    {
        JOptionPane.showMessageDialog(null, "Please Enter an Email Address.");
        return;
    }

    //test cell number

    contactPhone = phoneField.getText();
    try
    {
        Integer.parseInt(contactPhone);
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(null, "Please Enter a valid Phone Number.");
        return;
    }

    String columns2[] =  {  contactName, contactAge, contactEmail, contactPhone  };

    //write data to file
    try{
        for (int i = 0; i < columns2.length; i++){
            fw.write(columns2[i].toString() + ", ");
          }
        fw.write("\r\n");
        fw.flush();
        fw.close();
Rainhider
  • 806
  • 1
  • 17
  • 31

2 Answers2

1

If you get NullPointerException during writing in file, there is two possibilities:

  1. You may not open the file. For example because of forgetting calling the constructor of FileWriter.

  2. You don't have any permission to open the file and write into it.

If you got the exception only when you are run it using TextPad, I think the second problems occurred. You don't have permission.

boomz
  • 657
  • 5
  • 21
  • Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at Wk3Beets.enterContact(Wk3Beets.java:175) at Wk3Beets$1.actionPerformed(Wk3Beets.java:99) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:20 18) – Rainhider Mar 31 '13 at 00:35
  • thanks...this helped me to check where i was initializing the filewriter! – Rainhider Mar 31 '13 at 00:43
0

Try To run your TextPad in Administrator Mode

Right Click on Textpad icon -> Run as administrator

& then RUN above program

i sure your program get executed properly.

Sangharatna
  • 118
  • 7