-2

I am getting a NullPointerException although I am giving the values. I have a DefaultTableModel called model1. I want to multiply the values of column 4 and 5 and add it to column 6. I made three rows. The value at 4,5 of the first two rows gets multiplied and added on column 6 but the value of the third row doesn't display on the column and generates an exception.

Here's the error block-

for(int i = 0; i <= model1.getRowCount();i++){
    Double d = Double.parseDouble((String) model1.getValueAt(i, 4));
    Double d2 = Double.parseDouble((String) model1.getValueAt(i, 5)); //exception
    Double d3 = d * d2;
    model1.setValueAt(d3, i, 6);
}

Here's the exception-

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at Busy.saver(Busy.java:246)
    at Busy.lambda$inventory$12(Busy.java:233)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2237)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2295)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4889)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4526)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4467)
    at java.awt.Container.dispatchEventImpl(Container.java:2281)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    BUILD SUCCESSFUL (total time: 48 seconds)

Why am I getting this exception?

Here's the MCVE-

import java.awt.*;
import java.io.Serializable;
import javax.swing.*;
import javax.swing.table.*;
public class Mcve extends JPanel{
    String data[][] ={{""}};
    String row[] = {"#","Item Name","HSN/SAC","Description","Qty.","Rate","Price"};
    DefaultTableModel model = new DefaultTableModel(data, row);
    JTable table = new JTable(model);
    JScrollPane pane = new JScrollPane(table);

    public void mainPage() {
        Mcve obj = new Mcve();
        JFrame frame = new JFrame("MCVE");
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        JInternalFrame iframe = new JInternalFrame();
        JButton save , add;
        save = new JButton("Save");
        add = new JButton("Add Item");
        save.setSize(75,40);
        add.setSize(85,40);
        iframe.setTitle("Inventory");
        iframe.add(pane);
        iframe.add(save, BorderLayout.WEST);
        iframe.add(add, BorderLayout.SOUTH);
        frame.add(iframe);
        iframe.setClosable(true);
        save.setVisible(true);
        add.setVisible(true);
        iframe.setVisible(true);
        frame.setVisible(true);
        save.addActionListener((ActionEvent) ->{
            saver();
        });
        add.addActionListener((ActionEvent) -> {
            rowAdder();
        });
    }
    public void saver(){
        for(int i = 0; i<=model.getRowCount();i++){
            Double d= Double.parseDouble((String) model.getValueAt(i,4));
            Double d2= Double.parseDouble((String) model.getValueAt(i,5));
            Double d3=d*d2;
            model.setValueAt(d3,i,6);
        }
    }
    public void rowAdder(){
        String row[][] = {};
        model.addRow(row);
    }
    public static void main(String[] args) {
        Mcve obj = new Mcve();
        obj.mainPage();
    }
} 
Michael
  • 41,989
  • 11
  • 82
  • 128
  • 3
    Does `model1.getValueAt(i,5)` by any chance return `null`? `Double.parseDouble((String)null)` is certainly going to raise a nullpointerexception – ernest_k Jun 14 '18 at 11:44
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – azro Jun 14 '18 at 11:52
  • The dup is mostly point the fact of calling an method on a `null` value @azro, not passing a `null` to a method (one that is not develop by us). So here, I don't think the NPE dup is really helpful. Reading the manual is though ! – AxelH Jun 14 '18 at 11:56
  • 1
    Please provide a [mcve] since you are not agreeing with our solution for the NPE. – AxelH Jun 14 '18 at 12:27
  • Could you add to your code `System.out.println(i + ": " + model1.getValueAt(i, 4) + " " + model1.getValueAt(i, 5) );` as the first line in the loop. Then could you [edit](https://stackoverflow.com/posts/50856723/edit) your question to show us what it prints. This will help us to understand what's going on – vincrichaud Jun 14 '18 at 12:55
  • i have added mcve check now –  Jun 14 '18 at 13:04
  • 0: 5 5 1: 5 5 2: 5 null I can't believe but I am giving the same value 5 in place of null but why it is printing null –  Jun 14 '18 at 13:07
  • 1
    Check the edit @noobprogrammer I think you can find the reason and the solution. – AxelH Jun 14 '18 at 13:27

3 Answers3

2

Columns are zero-indexed. So columns 4 and 5 are indexes 3 and 4.

Your sixth column is presumably empty if it's a placeholder for a result, so mistakenly calling model1.getValueAt(i, 5) is returning null because the cell is empty.

Double d = Double.parseDouble((String) model1.getValueAt(i, 3));
Double d2 = Double.parseDouble((String) model1.getValueAt(i, 4));
Double d3 = d * d2;
model1.setValueAt(d3, i, 5);
Michael
  • 41,989
  • 11
  • 82
  • 128
  • no the columns are 4 and 5 and result column 6 is also correct but the difference is value at column 4 and 5 of the first two row gives correct result at column 6 but the third row don't display value at column 6 it generates exception –  Jun 14 '18 at 12:07
2

Just using the Stacktrace and the documentation :

We can see that this is the call of Double.parseDouble that throws the exception.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at
java.lang.Double.parseDouble(Double.java:538) at
Busy.saver(Busy.java:246)

And the documentation of Double.parseDouble tells you :

Throws:
- NullPointerException - if the string is null

So you are passing a null value to Double.parseString.


The reason for me is that you are still in "edit" mode when you click the button to save, you will not commit the value so the cell will still be seen as empty (null) by the model. You can force the end of the edition at the beginning of saver method to be sure.

TableCellEditor editor = table.getCellEditor();
if (editor != null) {
    editor.stopCellEditing();
}

From Guillaume answer.

Of course, this will not prevent an exception if the cell is not a numeric value (empty or not numeric). So the solution would be to catch the exception for each row.

for (int i = 0; i <= model.getRowCount(); i++) {
    try{
        Double d = Double.parseDouble((String) model.getValueAt(i, 4));
        Double d2 = Double.parseDouble((String) model.getValueAt(i, 5));
        Double d3 = d * d2;
        model.setValueAt(d3, i, 6);
    } catch (NullPointerException | NumberFormatException e){
        model.setValueAt("N/A", i, 6);
    }
}

Then, you can check vincrichaud answer to correct the java.lang.ArrayIndexOutOfBoundsException you will get from the loop you are using.

AxelH
  • 14,325
  • 2
  • 25
  • 55
  • but i am giving the values at column 4 and 5 of the first two row it shows correct result at correct place but the third doesn't show any result at column 6 it generates exception –  Jun 14 '18 at 12:11
  • 1
    The documentation doesn't lie @noobprogrammer, it should be the only possible solution. Use a debugger or simply print the value before the parsing ( `System.out.println(model1.getValueAt(i, 4) + " " + model1.getValueAt(i, 5) );` – AxelH Jun 14 '18 at 12:13
  • you are correct the document doesn't lie but i am not lying too –  Jun 14 '18 at 12:16
  • But you can make mistake. Please provide a [mcve] if you don't agree with the solution proposed. – AxelH Jun 14 '18 at 12:17
  • Thanks I can't believe this that this also can be reason of npe well thanks you figured it out thank you –  Jun 14 '18 at 16:03
  • Yep @noobprogrammer, the `JTable` is a complex component with a lot of layer. This is tricky to use. – AxelH Jun 14 '18 at 18:03
1

for(int i = 0; i<=model1.getRowCount();i++) You will loop once too much. You need to go i<model1.getRowCount())

As mentionned by AxelH in his comment, this won't solve your NPE problem. But that's still an error in your code that will cause problem as soon as you solve your NPE.

vincrichaud
  • 2,218
  • 17
  • 34
  • That's a nice catch ! But that's solving the `ArrayIndexOutOfBOundsException` that will happen later on [`DefaultTableModel.getValueAt`](https://docs.oracle.com/javase/7/docs/api/javax/swing/table/DefaultTableModel.html#getValueAt%28int,%20int%29). But this is gonna be a problem soon enough (once the NPE will be fixed). – AxelH Jun 14 '18 at 12:26
  • @noobprogrammer as explain by AxelH, it won't solve your NPE. But it solve a problem that you'd face when your NPE is resolved. – vincrichaud Jun 14 '18 at 12:54