0

I'm receiving the error:

Exception in thread "main" java.lang.NullPointerException
at javaapplication21.AnimalDB1.createAnimal(AnimalDB1.java:80)
at javaapplication21.AnimalDB1.main(AnimalDB1.java:137)

I have gone through other posts looking to see what would possibly be causing this but have not been able to figure it out. I have another program that performs mostly the same functions and doesn't have a problem. I've been trying to figure this out for a while and think that I need another set of eyes to point out what I'm obviously missing. I italicized the lines in question from the error. Any help would be greatly appreciated.

import static java.lang.System.out;
import java.sql.*;
import java.sql.SQLException;

public class AnimalDB1 {

private static final String url = "jdbc:derby://localhost:1527/AnimalDB";
private static final String user = "testuser";
private static final String pwd = "admin";
private static Connection connection = null;
private static int nextId = 1;
private boolean tablesCreated = false;

private static void createConnection() throws ClassNotFoundException {
try{
    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
    connection = DriverManager.getConnection(url);
    System.out.println("Connection Successful");
}
catch(SQLException e){}
}

// Increments the ID number for each animal
private void incId(){
    AnimalDB1.nextId++;
}

private void createTable() throws SQLException{
    Statement statement = null;

    try{
    StringBuilder sb = new StringBuilder("");
        sb.append("CREATE table Animals (\n");
            sb.append("ID INTEGER NOT NULL,\n");
            sb.append("AnimalName varchar(30),\n");
            sb.append("Char1 varchar(30),\n");
            sb.append("Char2 varchar(30),\n");
            sb.append("Char3 varchar(30),\n");
            sb.append("Char4 varchar(30),\n");

        sb.append(")\n");

        // Get a statement from the connection so we can execute the query.
        statement = connection.createStatement();
        statement.executeUpdate(sb.toString());
        tablesCreated = true;
    } catch (Exception e){
        System.out.println(e.getMessage());
    } finally {
        if(statement != null){
            try {
                statement.close();
            } 
            catch(Exception e){
                System.err.println(e.getMessage());
                System.exit(0); // Something is terribly wrong so just quit the program.
            }
        }
    }
}

private void createAnimal (String animalName, String char1, String char2, String char3, String char4){
    PreparedStatement pState = null;
    try{
        String sql = "Insert into Animal values (?,?,?,?,?,?)";
        *pState = connection.prepareStatement(sql);*
        pState.setInt(1, nextId);
        pState.setString(2, animalName);
        pState.setString(3, char1);
        pState.setString(4, char2);
        pState.setString(5, char3);
        pState.setString(6, char3);

        pState.executeUpdate();
        pState.close();
        incId();
    }
    catch (SQLException e){
        System.err.println(e.getMessage());
    }
}

private static void closeConnection() {
    try {
        // Close the connection
        if(connection != null){
            connection.close();
        }

    } catch(Exception e){
        System.out.println(e.getMessage());
    }
}

public static void queryAnimals() throws SQLException{
    String query = "SELECT * FROM Animal";
    try{
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()){
            out.print(rs.getInt(nextId) + " ");
            out.print(rs.getString("animalName") + "  ");
            out.print(rs.getString("char1") + ", ");
            out.print(rs.getString("char2") + ", ");
            out.print(rs.getString("char3") + ", ");
            out.print(rs.getString("char4") + ", ");                               
        }
    }catch (SQLException se){}

}
public static void main(String[] args) throws ClassNotFoundException, SQLException {

    System.out.println("Welcome to the Animal Database");
    System.out.println("The list below shows all of the animals currently "
                       + "stored in the database");

    createConnection();

    AnimalDB1 db = new AnimalDB1();

    db.createTable();

    *db.createAnimal("Huskie", "White", "Long hair", "Four legs", "Paws");*
    db.createAnimal("Salmon", "Silver", "Scales", "Fins", "Swims");
    db.createAnimal("Crow", "Black", "Feathers", "Claws", "Flies");
    db.createAnimal("Black Snake", "Black", "Scales", "No Appendages", "Slithers");              

    AnimalDB1.queryAnimals();

    closeConnection();
}

}

Bails
  • 183
  • 1
  • 1
  • 7
  • 2
    You're ignoring the possible exception in `createConnection`, so how do you know if `connection` is `null` or not (or why) – MadProgrammer Sep 15 '15 at 02:16
  • You didn't pass in the user and passwd arguments to getConnection(), even though you have variables for them. – WillShackleford Sep 15 '15 at 02:22
  • @Jason The root cause is poorly structured code, as it always is with NPEs and indeed many other things as well. In this instance the ultimate issue was failing to open the connection. Still a duplicate. – user207421 Sep 15 '15 at 02:29
  • 1
    @Jason No `NullPointException` is EVER the cause of the problem, they are ALL symptom's of something else, however, the tools and the techniques for finding out WHY those occur are pretty much the same. Debugging, debug messages and other diagnostic tools, which should have been employed before posting - Just saying – MadProgrammer Sep 15 '15 at 02:29
  • 1
    @Jason Also, you shouldn't have to create a new instance of the driver, using `Class.forName` should register the driver with the `DriverManager`, which will use the "url" to find and create a suitable instance of the driver. The problem still falls to ignoring exceptions without providing suitable diagnostics or logging – MadProgrammer Sep 15 '15 at 02:32
  • The reopen vote is utterly ridiculous. If we're going to have non-duplicate questions for every possible distinct cause of NullPointerExceptions there is no hope for this site. – user207421 Sep 15 '15 at 03:15

0 Answers0