2

I'm getting a really annoying error, saying I'm getting a null pointer exception but there's an if statement to check to see if the text is null before proceeding:

    public String[] getFileData() throws IOException
{
    String file_name = "C:/Users/Liloka/Source/textfiles/Lines.txt";

    try {
        ReadFile file = new ReadFile(file_name);
        aryLines = file.OpenFile();

        for(int i =0; i<aryLines.length; i++)
        {
            System.out.println(aryLines[i]);
        }
    }

    catch(IOException e)
    {   
        System.out.println(e.getMessage());
    }
    return aryLines;
}

public void actionPerformed(ActionEvent evt)
{
    if(evt.getSource() == enterBtn)
    {
        String Text = textToAdd.getText();
        if(!(Text.equals(null)))
        {
            RF.addNewElement(Text);
            System.out.println(Text);

            try
            {
                RF.writeToFile();
                getFileData();
            }
        catch(Exception e)
            {

            }
        }
        else    JOptionPane.showMessageDialog(null, "Please enter a word!");
    }

}

The only time it even considered the 'else' was through this:

    if(Text.equals(null));

I've also tried doing:

   if(Text != null));

which has worked for me in the past but not now! Other classes are:

public String[] OpenFile() throws IOException
{
    FileReader fr = new FileReader(path);
    BufferedReader br = new BufferedReader(fr);

    int numberOfLines = readLines();
    textData = new String[numberOfLines];
    int i;
        for(i=0; i<numberOfLines; i++)
        {
                textData[i] = br.readLine();
        }

    br.close();
    return textData;
}

int readLines() throws IOException
{
    FileReader file_to_read = new FileReader(path);
    BufferedReader bf = new BufferedReader(file_to_read);

    String aLine;
    numberOfLines=0;

    while((aLine = bf.readLine()) != null)
    {
        numberOfLines++;
    }
    //numberOfLines++;
    bf.close();
    return numberOfLines;
}

public void addNewElement(String newElement)
{   
    String texticles = newElement;
    numberOfLines = numberOfLines++;
    textData[numberOfLines] = texticles;
    //numberOfLines++; //Increments numberOfLines for the next element to be added
}

public void writeToFile() throws IOException
{
    FileWriter fstream = new FileWriter(path);
    BufferedWriter outFile = new BufferedWriter(fstream);
    //numberOfLines++;

        outFile.write(textData[numberOfLines]);
        //outFile.write(",");

        outFile.write("\r\n");

    outFile.close();
}

Thank you, again!

Error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at textfiles.JListExample.actionPerformed(JListExample.java:115)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)

I get the error when I've typed or not typed something and pressed the enter button.

This is the error for

if(Text != null)

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at textfiles.JListExample.actionPerformed(JListExample.java:115)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
liloka
  • 1,016
  • 4
  • 14
  • 29
  • In what like do you get the exception? Maybe it's not related to the `Text` variable... – Jordão Sep 13 '11 at 17:25
  • two things. Text should start with a lower case. Then you are invoking an equal method on the String object. If the string is null, you will get a Null pointer exception. If(text != null ) should work, unless if you have some logical mistake. I believe you could have a double negation. if(!(text != null)) or some other simple error like that. – uncaught_exceptions Sep 13 '11 at 17:29
  • 1
    And what is at line: **at textfiles.JListExample.actionPerformed(JListExample.java:115)** – John B Sep 13 '11 at 17:34
  • There is no double negation, I've checked for that. I also changed String Text to text and it is still giving me the same error! This is why I don't understand why I'm getting this error. – liloka Sep 13 '11 at 17:34
  • 1
    Which line is 115? My guess is that **RF** is not initialized. – John B Sep 13 '11 at 17:37
  • 1
    a different variable is null. Answer John B's question to find out which. The key is to look carefully at the error message as it's not a meaningless bunch of garbage, but usually contains the information that would allow you to solve this yourself. – Hovercraft Full Of Eels Sep 13 '11 at 17:38
  • I've decalred RF as this: ReadFile RF; RF.addNewElement(text); Is line 115 and I'm not guessing JohnB is right. ReadFile is just another class file, so can I call an object of that? – liloka Sep 13 '11 at 17:41
  • You're not answering the question regarding which line is **line 115**, and it's not how you ***declare*** RF, but how you ***initialize*** it. Where do you call `RF = new ReadFile(...)`? – Hovercraft Full Of Eels Sep 13 '11 at 17:42
  • I've not called RF = new ReadFile because when I've done that in another method I needed to pass in a string called path, but in this I don't need to pass it a string. – liloka Sep 13 '11 at 17:44
  • Line 115 is RF.addNewElement(text); I did answer >.0 – liloka Sep 13 '11 at 17:48
  • Then RF is null as we've been telling you. You need to fix that. – Hovercraft Full Of Eels Sep 13 '11 at 17:49
  • WELL I've fixed the NullPointerException, so thank you :) I just initialised the ReadFile global instead of local and now I'm back to ArrayIndexOutOfBounds :) brilliant. But thank you! – liloka Sep 13 '11 at 17:53

2 Answers2

16
 if(Text.equals(null));

The above will throw a NullPointerException each time Text is null. Anytime you use the "." operator on null you get a NullPointerException.

If you are getting a NPE after if(Text != null), please post the stack trace.

John B
  • 32,493
  • 6
  • 77
  • 98
  • 2
    +1. Very good point. Also, the comparison of Text.equals(null) is kind of pointless, since it will either throw the NPE or return `false`. The comparison of `null == Text` should instead be used. Also, as a style guideline, variables in Java should be lower case. – Peter Sep 13 '11 at 17:27
  • don't you wish there were an `Objects.equal(a, b)` that handles null correctly? – Jason S Sep 13 '11 at 17:29
  • 1
    There is, Guava's Objects.equal(a,b). [link](http://docs.guava-libraries.googlecode.com/git-history/v9.0/javadoc/com/google/common/base/Objects.html#equal(java.lang.Object, java.lang.Object)) – John B Sep 13 '11 at 17:29
  • @Peter, I just tried the different ways of comparing Strings as I was told in college you can't compare two strings like this: String a == String b; – liloka Sep 13 '11 at 17:31
  • @Jason S, check out Guava's Objects class. Sorry the link is messed up. Not sure how to fix. – John B Sep 13 '11 at 17:32
  • You can, it just depends what you are trying to do. It won't compare their characters to each other. Comparing strings with just the == will tell you if both strings are pointing to the same String Object or not. – w.donahue Sep 13 '11 at 17:34
  • 3
    @liloka: Per **String a == String b**. It is true that you should never do this for two Strings but it is appropriate when comparing against **null**. **null** is not a String it is a blank reference and where you compare it against a String you are checking to see if the String is also a blank reference. – John B Sep 13 '11 at 17:42
  • Well I knew comparing String a == String b wouldn't throw a compilation error, just for our exam it was a big no no so they just told us don't ever do it! – liloka Sep 13 '11 at 17:46
  • @liloka: It is true that when comparing _non-null_ Strings for equality, you should use `equals()`. (At least the String you are calling `equals()` on should be guaranteed to non-null) But if you need to check whether a String, or any Object is `null`, you should use the `==` operator. See the Javadoc for `Object.equals()` for more information. – Peter Sep 13 '11 at 18:00
  • This is why you should use [Yoda Conditions](http://blog.codinghorror.com/new-programming-jargon/) to check for `null` – Richard Le Mesurier May 21 '14 at 12:49
0

My guess is either textToAdd or RF is null.

If textToAdd is a JTextComponent (or subclass, but I'm guessing here), then its getText() method CANNOT return null. Therefore, Text CANNOT be null, as this test shows.

package test;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class TextComponentTest extends JFrame {
    JTextField tf;

    public TextComponentTest() {
        super();
        tf = new JTextField();
        getContentPane().add(tf);
    }

    public static void main(String[] args) {
        TextComponentTest test = new TextComponentTest();
        test.setVisible(true);

        String s = test.tf.getText();
        System.out.println(">" + s + "<");
        System.out.println(">" + s.length() + "<");

        test.tf.setText(null);
        s = test.tf.getText();
        System.out.println(">" + s + "<");
        System.out.println(">" + s.length() + "<");
    }
}

Output is:

><
>0<
><
>0<
Paul Grime
  • 14,970
  • 4
  • 36
  • 58
  • textToAdd is a JTextField.. (I know I need to work on my variable names but I'm just practising atm! - before I get told off) In my previous programs it has worked and considering the line it's throwing a wobbly on in 115 and that's the line for RF.addNewElement(); it's that.. – liloka Sep 13 '11 at 17:47
  • So that means **RF** is null. – John B Sep 13 '11 at 17:49
  • 1
    Excellent! Glad my logic was sound - not glad that your app isn't working yet! – Paul Grime Sep 13 '11 at 17:50