Solved

Null Pointer Exception?

Posted on 2004-08-25
14
370 Views
Last Modified: 2010-05-18
Keep getting the Null Pointer Exception, any ideas?

Here is the JSP:

<%@page contentType="text/html" %>
<%@page pageEncoding="UTF-8" %>
<%@page import="java.sql.*" %>
<%@page import="pt.*" %>
<html>
    <head><title>Update a Record</title></head>
    <body>
<% TrainingConnect trainingConnect = new TrainingConnect();%>
<%
String Date = request.getParameter("date");
String mode = request.getParameter("mode");
String submit = request.getParameter("submit");
String ActPushupSet = request.getParameter("ActPushupSet");
String ActPushupRep = request.getParameter("ActPushupRep");
String ActSitupSet = request.getParameter("ActSitupSet");
String ActSitupRep = request.getParameter("ActSitupRep");
String ActRun = request.getParameter("ActRun");
String comment = request.getParameter("comment");
String msg = "";
String datenow = "NOW()";
if (Date.equals(null)) {
   %>You cannot access this page directly!<%
    } else {
if (ActPushupSet != null){
    trainingConnect.dbConnect();
    if((trainingConnect.updateRecord(Date, ActPushupSet, ActPushupRep, ActSitupSet, ActSitupRep, ActRun, comment, datenow)) > 0) {
        msg = "Record successfully updated!";
    } else {
        msg = "There was an error updating the record!";
        }
    }

if (trainingConnect.selectRecord(Date)) {
    while (trainingConnect.getNextItem()) {
        String week = trainingConnect.getItemNameString("week");
        String PushupGoalSet = trainingConnect.getItemNameString("gPushupSet");
        String PushupGoalRep = trainingConnect.getItemNameString("gPushupRep");
        String PushupActSet = trainingConnect.getItemNameString("aPushupSet");
        String PushupActRep = trainingConnect.getItemNameString("aPushupRep");
        String SitupGoalSet = trainingConnect.getItemNameString("gSitupSet");
        String SitupGoalRep = trainingConnect.getItemNameString("gSitupRep");
        String SitupActSet = trainingConnect.getItemNameString("aSitupSet");
        String SitupActRep = trainingConnect.getItemNameString("aSitupRep");
        String RunGoal = trainingConnect.getItemNameString("gRun");
        String RunAct = trainingConnect.getItemNameString("aRun");
        String Comment = trainingConnect.getItemNameString("comment");
        String Update = trainingConnect.getItemNameString("updated");
        %>
        <form method="post" action="add.jsp">
            <table>
        <% if (submit != null) {
            %>
            <tr>
                <th colspan='2'><%= msg %></th>
            </tr>
            <%
            }
            %>
            <tr>
            <td>Date:</td>
            <td><input type="text" maxlength="30" size="20" name="date" value="<%= Date %>" disabled></td>
            <tr>
            <tr>
            <td>Week:</td>
            <td><input type="text" maxlength="30" size="20" name="week" value="<%= week %>" disabled></td>
            <tr>
            <tr>
            <td>Actual Pushup Set:</td>
            <td><input type="text" maxlength="30" size="20" name="ActPushupSet" value="<%= PushupActSet %>"></td>
            <tr>
            <tr>
            <td>Actual Pushup Reps:</td>
            <td><input type="text" maxlength="30" size="20" name="ActPushupRep" value="<%= PushupActRep %>"></td>
            <tr>
            <tr>
            <td>Actual Situp Set:</td>
            <td><input type="text" maxlength="30" size="20" name="ActSitupSet" value="<%= SitupActSet %>"></td>
            <tr>
            <tr>
            <td>Actual Situp Reps:</td>
            <td><input type="text" maxlength="30" size="20" name="ActSitupRep" value="<%= SitupActRep %>"></td>
            <tr>
            <tr>
            <td>Actual Run:</td>
            <td><input type="text" maxlength="30" size="20" name="ActRun" value="<%= RunAct %>"></td>
            <tr>
            <tr>
            <td>Comment:</td>
            <td><input type="textarea" rows="10" cols="10" name="comment" value="<%= comment %>"></td>
            <tr>
            <tr>
                <td><input type="submit" name="submit" value="Update the Record!"></td>
            </tr>
        <%
       
        }
    }
trainingConnect.dbDisconnect();
}
%>
        </form>
        </table>
        </div>

    </body>
</html>

</body>
</html>

And the .java:

/*
 * TrainingConnect.java
 *
 * Created on August 24, 2004, 12:04 PM
 */
package pt;

import java.sql.*;
/**
 *
 * @author  marcadam
 */
public class TrainingConnect {
   
    private Driver drv = null;
    private Connection conn = null;
    private ResultSet rs = null;
    private Statement stmt = null;
    /** Creates a new instance of TrainingConnect */
    public TrainingConnect() {}
   
    public void dbConnect() throws Exception {
        drv = (Driver)
    Class.forName("com.mysql.jdbc.Driver").newInstance();
        //conn = DriverManager.getConnection("jdbc:mysql:///news?user=&password=");
        conn = DriverManager.getConnection("jdbc:mysql:///pt?user=&password=");
    }
    public boolean getNextItem() throws Exception {
        boolean ret = rs.next();
        return(ret);
    }
    public String getItemNameString(String columnName) throws Exception {
        String name = rs.getString(columnName);
        return(name);
    }
    public float getItemNameFloat(String columnName) throws Exception {
        float name = rs.getFloat(columnName);
        return(name);
    }
    public boolean selectRecords() throws Exception {
        String query = "SELECT * FROM pt WHERE updated > '0000-00-00 00:00:00' ORDER BY week";
        stmt = conn.createStatement();
        rs = stmt.executeQuery(query);
        boolean ret = false;
        if (rs != null)
            ret = true;
        return(ret);
    }
        public boolean selectRecord(String Date) throws Exception {
        String query = "SELECT * FROM pt WHERE wdate = (" + Date + ")";
        stmt = conn.createStatement();
        rs = stmt.executeQuery(query);
        boolean ret = false;
        if (rs != null)
            ret = true;
        return(ret);
    }
    public int updateRecord(String Date, String ActPushupSet, String ActPushupRep, String ActSitupSet, String ActSitupRep, String ActRun, String comment, String updated) throws Exception {
        String query = "UPDATE pt SET (aPushupSet, aPushupRep, aSitupSet, aSitupRep, aRun, comment, updated) VALUES (" + ActPushupSet + "), (" + ActPushupRep + "), (" + ActSitupSet + "), (" + ActSitupRep + "), (" + ActRun + "), (" + comment + "), (" + updated + ") WHERE wdate = (" + Date + ")";
        stmt = conn.createStatement();
        int ret = stmt.executeUpdate(query);
        return(ret);
    }
    public void dbDisconnect() throws Exception {
        stmt.close();
        conn.close();
    }
   
}

   
It;s saying the Null Pointer is on selectRecord, but I can't find an issue with it.

Any help is appreicated.
0
Comment
Question by:k41d3n
  • 7
  • 4
  • 2
14 Comments
 
LVL 35

Accepted Solution

by:
TimYates earned 500 total points
ID: 11893084
1) Can you post the actual stack trace from the exception?
2)  Just fram a quick scan of your code, I would recommend that you change your SQL to using PreparedStatements:

ie:

    private Statement stmt = null;
    ....
    public boolean selectRecord(String Date) throws Exception {
        String query = "SELECT * FROM pt WHERE wdate = (" + Date + ")";
        stmt = conn.createStatement();
        rs = stmt.executeQuery(query);
        boolean ret = false;
        if (rs != null)
            ret = true;
        return(ret);
    }

becomes:

    private PreparedStatement stmt = null;
    ....
    public boolean selectRecord(String Date) throws Exception {
        String query = "SELECT * FROM pt WHERE wdate = ?";
        stmt = conn.prepareStatement( query );
        stmt.setString( 1, Date ) ;
        rs = stmt.executeQuery();
        boolean ret = false;
        if (rs != null)
            ret = true;
        return(ret);
    }

and all of the other methods too
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11893109
Also, you seem to be using Strings to represent date fields in your database..l

This isn't generally a good idea, as it depends on the locale and date format of the database, not the user...  With prepared statements, you can do stmt.setDate( col, date ) instead of using setString for everything...

First things first though... can you post your stacktrace?
0
 
LVL 19

Expert Comment

by:ramazanyich
ID: 11893168
Could you send  a stacktrace from your application server ?
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 2

Author Comment

by:k41d3n
ID: 11893229
Here is the stack, I will change all my statements to Prepared. Thanks for that.

2004-08-25 10:02:17 StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
      at org.apache.jsp.add_jsp._jspService(add_jsp.java:65)
      at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:133)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
      at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:311)
      at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:301)
      at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:248)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:284)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:204)
      at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:305)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:233)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:204)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:257)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:567)
      at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:245)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:199)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:567)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:184)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:164)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:149)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:567)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:156)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:567)
      at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:972)
      at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:206)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:833)
      at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:732)
      at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:619)
      at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:688)
      at java.lang.Thread.run(Thread.java:534)

0
 
LVL 19

Expert Comment

by:ramazanyich
ID: 11893370
I tried to put your JSP and java class in my Tomcat and I got exception on line
if(Date.equals(null))

Replace it by
if(Date == null)

0
 
LVL 2

Author Comment

by:k41d3n
ID: 11893449
Got the same error.

The only reason why I use that first date column as a string is because that is how it was given to me.

they were all manually entered in the format 16-Aug-2004, at the end I tacked on an updated field that is a bonafide timestamp field.

Is there a way to go through the database and convert them all to dates? If that is the issue causing the null pointer.


0
 
LVL 19

Expert Comment

by:ramazanyich
ID: 11893663
another problem can be that probably connection to MySQL db was not successful.
Just to be sure could you try to put following statement in selectRecords ?

if(conn ==null){
throw new Exception("NO CONNECTION TO MYSQL DB");
}
0
 
LVL 2

Author Comment

by:k41d3n
ID: 11893698
No, there is a connection to mySQL, I know this because I have another JSP I use to call the same class and it has zero problems displaying the data.
0
 
LVL 19

Expert Comment

by:ramazanyich
ID: 11893769
did you also replaced if(Date.equal(null)) by if(Date == null) ?
0
 
LVL 2

Author Comment

by:k41d3n
ID: 11893788
yes, still get the null pointer :(
0
 
LVL 2

Author Comment

by:k41d3n
ID: 11896606
I fixed this on my own.

Request to have it removed.
0
 
LVL 2

Author Comment

by:k41d3n
ID: 11902184
I don't know what the root cause of the Null Pointer was, but I realize it was occuring in the fashion that I was checking to see if the form had been submitted, and if it was, update the database, and if it wasn't to display the form.

Basically I was trying to put it all in one form.

My solution was to put the form on one page, and the form action in another page. That way, I didn't have to worry about a null pointer exception when trying to request.getParameter(); a variable that could conflict.

0
 
LVL 2

Author Comment

by:k41d3n
ID: 11902202
Actually, upon reading over the thread again, I see that Tim gave the idea to use prepared statements. He should get some points for his Good Samaritan advice.

Sorry for the drama.

Thanks everyone for the help.
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How To Remove a Principal from HttpServletRequest 4 52
IE doesn't Invoke servlet in iframe 1 115
maven set up 2 175
mysql jsp example issue 32 53
The Nano Server Image Builder helps you create a custom Nano Server image and bootable USB media with the aid of a graphical interface. Based on the inputs you provide, it generates images for deployment and creates reusable PowerShell scripts that …
Smart phones, smart watches, Bluetooth-connected devices—the IoT is all around us. In this article, we take a look at the security implications of our highly connected world.
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question