AntonB
AntonB

Reputation: 1

Java: I'm having an issue connecting to a database from another class

I'm making a simple address book app. I have a DatabaseUtility class, which has one method, connectToDatabase() is responsible for pulling info from an embedded database (Java DB) and constructing Contact objects from it.

These Contact objects are then placed into an ArrayList and then the entire ArrayList is returned. Yes, I know this is poor programming. It makes more logical sense to have separate methods for connecting and constructing objects, but this is kind of a quick little project I'm doing for practice, and I think I can get by, right?

Anyways, I also have a ContactControl class which contains an instance of the DatabaseUtility class as one of it's fields, as well as a private ArrayList of Contacts as one of it's fields.

What I want is for the ArrayList in the ContactControl class to be instantiated by the return value of the connectToDatabase() method (which, as I've already mentioned, returns an ArrayList).

However, I keep getting an exception. It's not connecting to the database. It connects when I run the main method that I placed in the DatabaseUtility class, but when I run the main method from the ContactControl class, I get an exception.

My code is below:

Contact class:

package contactbook;

import java.io.IOException;
import java.io.ObjectStreamException;
import java.util.Date;

public class Contact {
    private int contactId;
    private String lastName;
    private String firstName;


    private String address;
    private String city;
    private String state;
    private String zip;
    private String picture;
    private String dob;

    public Contact()
    {
        contactId = 0;
        lastName =  "Doe";
        firstName = "John";
        dob = "01/01/1997";
        address = "123 ABC Dr.";
        city = "Pensacola";
        state = "FL";
        zip = "12345";
        picture = "default1.gif";
    }

    public Contact(int contactId, String lastName, String firstName, String address, String city, String state, String zip, String picture, String dob)
    {
        this.contactId = contactId;
        this.lastName = lastName;
        this.firstName = firstName;
        this.address = address;
        this.city = city; 
        this.state = state;
        this.zip = zip;
        this.picture = picture;
        this.dob = dob;
    }

    //setters
    public void setContactId(int contactId)
    {

    }

    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }

    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    public void setCity(String city)
    {
        this.city = city;
    }

    public void setState(String state)
    {
        this.state = state;
    }

    public void setZip(String zip)
    {
        this.zip = zip;
    }

    public void setPicture(String picture)
    {
        this.picture = picture;
    }

    public void setDob(String dob)
    {
        this.dob = dob;
    }

    //getters

    public int getContactId()
    {
        return contactId;
    }

    public String getLastName()
    {
        return lastName;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public String getAddress()
    {
        return address;
    }

    public String getCity()
    {
        return city;
    }

    public String getState()
    {
        return state;
    }

    public String getZip()
    {
        return zip;
    }

    public String getPicture()
    {
        return picture;
    }

    public String getDob()
    {
        return dob;
    }

}

DatabaseUtility class:

package contactbook;



import java.io.IOException;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Properties;

public class DataBaseUtility {


public ArrayList<Contact> connectToDatabase() throws Exception { 
    ArrayList<Contact> contacts = new ArrayList<Contact>();
try
    {
      // Step 1: "Load" the JDBC driver
      Class.forName("org.apache.derby.jdbc.ClientDriver"); 

      // Step 2: Establish the connection to the database 
      String url = "jdbc:derby://localhost:1527/ContactBook"; 
      Connection conn = DriverManager.getConnection(url,"app","app");  
      System.out.println("Connected!");
      Statement stat = null;
      stat = conn.createStatement();
        ResultSet rs = stat.executeQuery("SELECT * FROM PERSON");
        int id = 1;
      while(rs.next())
      {

          Contact contact = new Contact();
          contact.setContactId(id);
          System.out.println(id);
          String lastName = rs.getString("lastName");
          System.out.println(lastName);
          contact.setLastName(lastName);
          String firstName = rs.getString("firstName");
          System.out.println(firstName);
          contact.setFirstName(firstName);
          String address = rs.getString("address");
          System.out.println(address);
          contact.setAddress(address);
          String city = rs.getString("city");
          System.out.println(city);
          contact.setCity(city);
          String state = rs.getString("state");
          System.out.println(state);
          contact.setState(state);
          String zip = rs.getString("zip");
          System.out.println(zip);
          contact.setZip(zip);
          String picture = rs.getString("picture");
          System.out.println(picture);
          contact.setPicture(picture);
          Date dob = rs.getDate("dob");
          System.out.println(dob);
          contact.setDob("" + dob);
          contacts.add(contact);
          System.out.println("");
          contacts.add(contact);
          id++;
      }
    }
    catch (Exception e)
    {
      System.err.println("D'oh! Got an exception!"); 
      System.err.println(e.getMessage()); 
    } 
      return contacts;
  } 

public static void main(String[] args)
{
    DataBaseUtility dbu = new DataBaseUtility();
    try
    {
        dbu.connectToDatabase();
    }
    catch(Exception e)
    {
        e.getMessage();
    }

}
} 

ContactControl class:

package contactbook;

import java.util.ArrayList;


public class ContactControl {
    private DataBaseUtility dbu;
    private ArrayList<Contact> contacts;

    public ArrayList<Contact> createContacts() throws Exception
    {
        try
        {
            contacts = dbu.connectToDatabase();
        }
        catch(Exception e)
        {
            System.out.println("Error!");
        }

        return contacts;
    }

    public Contact getContact(int id)
    {
        Contact tact = new Contact();
        for(Contact c : contacts)
        {
            if(id == c.getContactId())
            {
                tact = c;
            }
        }
            return tact;
    }

    public static void main(String[] args)
    {
        ContactControl cc = new ContactControl();
        ArrayList<Contact> tacts = new ArrayList<>();
        try
        {
            tacts = cc.createContacts();
        }
        catch(Exception e)
        {
            System.out.println("Uh oh! Problem!");
        }


    }

}

Whenver I run the main method of the ContactControl class, I get the "Error!" message that you see in the try-catch block.

Upvotes: 0

Views: 75

Answers (1)

dogant
dogant

Reputation: 1386

I think the issue is that you're calling a null object in your ContactControl class.

contacts = dbu.connectToDatabase();

dbu is not initialized and basically it's null thus the NullPointerException. Since you're hiding actual exception messages from yourself with some custom messages you wouldn't see it.

Upvotes: 3

Related Questions