0

I am developing a software for my academic purpose. For that I am using Netbeans IDE,sqlite. When I run the code it gives me following error,

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 ProductInfo.getProductList(ProductInfo.java:109)
at ProductInfo.Show_Products_In_JTable(ProductInfo.java:126)
at ProductInfo.<init>(ProductInfo.java:44)
at ProductInfo$12.run(ProductInfo.java:658)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
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:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
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)

And here is the code,

import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

public class ProductInfo extends javax.swing.JFrame {

Connection conn=null;
ResultSet rs = null;
PreparedStatement pst=null;

public ProductInfo() {
initComponents();
conn=JavaConnect.ConnectDb();
Show_Products_In_JTable();

}
String imgpath=null;
int pos = 0;

public boolean checkInputs()
{
if(
      txt_name.getText() == null
   || txt_price.getText() == null
   || txt_AddDate.getSelectedDate().getTime() == null
  ){
    return false;
}
else{
    try{
        Double.parseDouble(txt_price.getText());

        return true;
    }catch(Exception ex)
    {
        return false;
    }
}
}

ImageIcon ResizeImage(String imagePath, byte[] pic)
{
ImageIcon myImage = null;

if(imagePath != null)
{
    myImage = new ImageIcon(imagePath);
}else{
    myImage = new ImageIcon(pic);
}

Image img = myImage.getImage();
Image img2 = img.getScaledInstance(lbl_img.getWidth(), lbl_img.getHeight(), Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(img2);
return image;

}

 public ArrayList<Product> getProductList()
{
    ArrayList<Product> productList  = new ArrayList<Product>();

    Connection conn=JavaConnect.ConnectDb();;
    ResultSet rs;
    PreparedStatement pst;




try {
    String sql = "SELECT * FROM ProductInfo";
    pst=conn.prepareStatement(sql);
    rs=pst.executeQuery();
    Product product;

    while(rs.next())
    {
        product = new Product(rs.getInt("ProductId"),rs.getString("Name"),Double.parseDouble(rs.getString("Price")),rs.getString("Date"),rs.getBytes("Image"));
        productList.add(product);
    }

} catch (SQLException ex) {
    Logger.getLogger(ProductInfo.class.getName()).log(Level.SEVERE, null, ex);
}

return productList; 

}




public void Show_Products_In_JTable()
{
ArrayList<Product> list = getProductList();
DefaultTableModel model = (DefaultTableModel)JTable_Products.getModel();
// clear jtable content
model.setRowCount(0);
Object[] row = new Object[4];
for(int i = 0; i < list.size(); i++)
{
    row[0] = list.get(i).getId();
    row[1] = list.get(i).getName();
    row[2] = list.get(i).getPrice();
    row[3] = list.get(i).getAddDate();

    model.addRow(row);
}

}

public void ShowItem(int index)
{
   txt_id.setText(Integer.toString(getProductList().get(index).getId()));
    txt_name.setText(getProductList().get(index).getName());
    txt_price.setText(Double.toString(getProductList().get(index).getPrice()));

try {
   Date addDate = null;
    addDate = new SimpleDateFormat("yyyy-MM-dd").parse((String)getProductList().get(index).getAddDate());

    txt_AddDate.getSelectedDate().setTime(addDate);

} catch (ParseException ex) {
    Logger.getLogger(ProductInfo.class.getName()).log(Level.SEVERE, null, ex);
}

lbl_image.setIcon(ResizeImage(null, getProductList().get(index).getImage()));
}
private void btn_deleteActionPerformed(java.awt.event.ActionEvent evt) {                                           
 if(!txt_id.getText().equals(""))
{
    try {
        String sql = "DELETE FROM ProductInfo WHERE ProductId = ? ";
        pst=conn.prepareStatement(sql);
        pst.execute();

        int id = Integer.parseInt(txt_id.getText());
        pst.setInt(1, id);
        pst.executeUpdate();
        Show_Products_In_JTable();
        JOptionPane.showMessageDialog(null, "Product Deleted");
    } 
    catch (SQLException ex) {
        Logger.getLogger(ProductInfo.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Product Not Deleted");
    }

}else{
    JOptionPane.showMessageDialog(null, "Product Not Deleted : No Id To Delete");
}
}
private void btn_insertActionPerformed(java.awt.event.ActionEvent evt) {                                           

if(checkInputs() && imgpath != null)
{
    try {

        String sql = "INSERT INTO ProductInfo(Name,Price,Date,Image) values(?,?,?,?) ";
        pst=conn.prepareStatement(sql);
        pst.execute();

        pst.setString(1, txt_name.getText());
        pst.setString(2, txt_price.getText());

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String addDate = dateFormat.format(txt_AddDate.getSelectedDate().getTime());

        pst.setDate(3, java.sql.Date.valueOf(addDate));



        InputStream img = new FileInputStream(new File(imgpath));

        pst.setBlob(4, img);



        pst.executeUpdate();
        Show_Products_In_JTable();

        JOptionPane.showMessageDialog(null, "Data Inserted");
    } catch (Exception ex) {
         JOptionPane.showMessageDialog(null, ex.getMessage());
    }
}else{
    JOptionPane.showMessageDialog(null, "One Or More Field Are Empty");
}
System.out.println("Name => "+txt_name.getText());
System.out.println("Price => "+txt_price.getText());
System.out.println("Date => "+txt_AddDate.getSelectedDate().getTime());
System.out.println("Image => "+imgpath);
}                                          

private void btn_ImageActionPerformed(java.awt.event.ActionEvent evt) {                                          
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));

FileNameExtensionFilter filter = new FileNameExtensionFilter("*.images", "jpg","png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION)
{
    File selectedFile = file.getSelectedFile();
    String path = selectedFile.getAbsolutePath();
    lbl_img.setIcon(ResizeImage(path, null));
    imgpath = path;
}
else{
    System.out.println("No File Selected");
}
}                                         

private void btn_updateActionPerformed(java.awt.event.ActionEvent evt) {                                           
if(checkInputs() && txt_id.getText() != null)
{

    // update without image
    if(imgpath == null)
    {
        try {
            String sql = "UPDATE ProductInfo SET Name = ?, Price = ?"
                    + ", Date = ? WHERE ProductId = ?";
            pst=conn.prepareStatement(sql);
            pst.execute();

            pst.setString(1, txt_name.getText());
            pst.setString(2, txt_price.getText());

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String addDate = dateFormat.format(txt_AddDate.getSelectedDate().getTime());

            pst.setDate(3, java.sql.Date.valueOf(addDate));

            pst.setInt(4, Integer.parseInt(txt_id.getText()));

            pst.executeUpdate();
            Show_Products_In_JTable();
            JOptionPane.showMessageDialog(null, "Product Updated");

        } catch (SQLException ex) {
            Logger.getLogger(ProductInfo.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    // update With Image
    else{
        try{
        InputStream img = new FileInputStream(new File(imgpath));

         String sql = "UPDATE ProductInfo SET Name = ?, Price = ?"
                    + ", Date = ? WHERE ProductId = ?";
            pst=conn.prepareStatement(sql);
            pst.execute();

            pst.setString(1, txt_name.getText());
            pst.setString(2, txt_price.getText());

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String addDate = dateFormat.format(txt_AddDate.getSelectedDate().getTime());
            //pst.setString(3, addDate);
            pst.setDate(3, java.sql.Date.valueOf(addDate));

            pst.setBlob(4, img);

            pst.setInt(5, Integer.parseInt(txt_id.getText()));

            pst.executeUpdate();
            Show_Products_In_JTable();
            JOptionPane.showMessageDialog(null, "Product Updated");

        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }
}else{
    JOptionPane.showMessageDialog(null, "One Or More Fields Are Empty Or Wrong");
}

}

Here are the variable declaration,

// Variables declaration - do not modify                     
private javax.swing.JTable JTable_Products;
private javax.swing.JButton btn_Image;
private javax.swing.JButton btn_delete;
private javax.swing.JButton btn_first;
private javax.swing.JButton btn_insert;
private javax.swing.JButton btn_last;
private javax.swing.JButton btn_next;
private javax.swing.JButton btn_previous;
private javax.swing.JButton btn_update;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lbl_date;
private javax.swing.JLabel lbl_id;
private javax.swing.JLabel lbl_image;
private javax.swing.JLabel lbl_img;
private javax.swing.JLabel lbl_name;
private javax.swing.JLabel lbl_price;
private datechooser.beans.DateChooserCombo txt_AddDate;
private javax.swing.JTextField txt_id;
private javax.swing.JTextField txt_name;
private javax.swing.JTextField txt_price;
// End of variables declaration                   

And this is the entity class,

public class Product {
private int id;
private String name;
private double price;
private String addDate; 
private byte[] picture;


public Product(int pid, String pname, double pprice, String pAddDate, byte[] pimg)
{
    this.id = pid;
    this.name = pname;
    this.price = pprice;
    this.addDate = pAddDate;
    this.picture = pimg;

}

public int getId()
{
    return id;
}

public String getName()
{
    return name;
}

public double getPrice()
{
    return price;
}

public String getAddDate()
{
    return  addDate;
}

public byte[] getImage()
{
    return picture;
}

I am a beginner and don't understand the error. Anyone please help me how to solve it?

Tabassum
  • 25
  • 2
  • 2
  • 8
  • The heuristic for debugging a NullPointerException is almost always the same: You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me. In the future, please search on the subject before posting, since this is too common a problem to post yet another NPE question. – Hovercraft Full Of Eels Mar 15 '17 at 13:32
  • So you need to study the variables on this line: `ProductInfo.java:109` to see what is null, and then search back to see *why*. Please check out the decent answers to be found in [this similar question](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Hovercraft Full Of Eels Mar 15 '17 at 13:32
  • I'm guessing that line 109 is this one: `productList.add(product);`. Please let me know if this is correct. If so, you'll want to read up on variable shadowing and NullPointerExceptions. – Hovercraft Full Of Eels Mar 15 '17 at 13:40
  • I've added a [second duplicate](http://stackoverflow.com/questions/30021160/nullpointerexception-java) that goes into this. Also look at [this search](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+nullpointerexception+variable+shadowing&*) – Hovercraft Full Of Eels Mar 15 '17 at 13:42
  • Reading those search you've provided and trying but still can't figure out how to solve. :( @HovercraftFullOfEels – Tabassum Mar 15 '17 at 13:58
  • Keep at it. Is the offending line the one I posted? – Hovercraft Full Of Eels Mar 15 '17 at 14:03
  • line 109 is: product = new Product(rs.getInt("ProductId"),rs.getString("Name"),Double.parseDouble(rs.getString("Price")),rs.getString("Date"),rs.getBytes("Image")); – Tabassum Mar 15 '17 at 14:06
  • Run your program again to make sure please. – Hovercraft Full Of Eels Mar 15 '17 at 14:07
  • Yes ProductInfo.java:109 is the line I posted. – Tabassum Mar 15 '17 at 14:13
  • No, what I meant is, if you run it again, check the line that the exception's stacktrace is telling you is causing the exception as it might have changed, and report to us which line that is. – Hovercraft Full Of Eels Mar 15 '17 at 14:18
  • Yes, I run the program again and the exception is the same. – Tabassum Mar 15 '17 at 14:22

0 Answers0