Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please i need some help with my programing assigment in Java. This is a typical

ID: 3815483 • Letter: P

Question

Please i need some help with my programing assigment in Java.

This is a typical 3 layer architecture. Now that we know about all the pieces, it's good to think about where they go. It's important to have an orgainziation. We would like to have all of the GUI in one place, and the DB code all in another place. It's not a difficult con- cept l. Create a 3 layer application in Java, where the top layer is the User Interface, the middle layer is the "business' layer, and the bottom layer is the database connectivity 2. The user interface will present a GUI to the user, asking them to enter some information, and to interact with the stored data Refer to your previous assignments. You can use your code or start from scratch. (The exact functionality provided to the user is deliberately vague here.) 3. Create a connection to a relational database using SQLite or MySQL 4. Create a single database table to hold information. Go back to the previous assignments, and re-use your classes, or modify them as you like. Recall that you will create the DB only once. You can just comment out the code that creates it if you like. Some people find a way to detect if the DB is al- ready there. That's fine, but not required 5. These requirements are taken from the previous assignment. This time the user is to be presented with a GUI that allows these things to be done. So the data is not hard coded, the user will fill in a GUI click a button to interact with the DB When you retrieve the data from the database it should popu- late the GUI to demonstrate that it is working 6. Demonstrate the insertion of a record into the database. Cre ate a method in the Data layer that takes a Person as a param- eter, and puts that data in the database. Insert several rec ords 7. Demonstrate the retrieval of information from the database Use SQL Select statements 8. Write a method called getPerson that returns a Person object This method retrieves the data for a Person from the database We also need to pass a parameter to identify what person You can use 'name' if you like, or if you find it easier to use the database generated ID that's fine too. This method returns the object that represents that person. This will require that you extract the data that is returned from the database, and call the Person constructor. Note that this is the data-ex- change between the relational database and the business layer. 9. Write a method called findAllPeople that returns an ArrayList of objects containing all the people in the database

Explanation / Answer

Person.java

package businesslayer;
public class Person implements Comparable<Person> {

   private String firstName;
   private String lastName;
   private String email;
   private String phoneNumber;

   public Person(String firstName, String lastName, String phoneNumber, String email) {
       setFirstName(firstName);
       setLastName(lastName);
       setEmail(email);
       setPhoneNumber(phoneNumber);
   }

   public String getFirstName() {
       return firstName;
   }

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

   public String getLastName() {
       return lastName;
   }

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

   public String getEmail() {
       return email;
   }

   public void setEmail(String email) {
       this.email = email;
   }

   public String getPhoneNumber() {
       return phoneNumber;
   }

   public void setPhoneNumber(String phoneNumber) {
       this.phoneNumber = phoneNumber;
   }

   @Override
   public int compareTo(Person obj) {
       return firstName.concat(lastName).compareTo(obj.getFirstName().concat(((Person) obj).getLastName()));
   }

   @Override
   public boolean equals(Object obj) {
       if ((obj instanceof Person)) {
           if (firstName.concat(lastName).equals(((Person) obj).getFirstName().concat(((Person) obj).getLastName()))) {
               return true;
           }
       }
       return false;
   }

   public String toString() {
       return "Name: " + firstName + " " + lastName + " Phone: " + phoneNumber + " Email: "
               + email + " ";
   }
}


AppData.java

package businesslayer;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import datalayer.DatabaseConnection;
import datalayer.DatabaseConnection;

// This is an example of using the Singleton pattern to make the application's data available throughout the
// application while guaranteeing that there is only one copy of it.

public class AppData {
   private static int i = 0; // used as iterator for the arrayList

   private List<Person> people = new ArrayList<Person>();

   // this is the reference to the single instance of the AppData class
   private static AppData appData = null;

   // A private constructor that is only called one time
   private AppData() {
   }

   // A public method to make the app Data available throughout the
   // application. The first time the method is called, the Single instance of
   // AppData is
   // created, each subsequent time, the one data object created is returned.
   public static AppData getAppData() {
       if (appData == null) {
           appData = new AppData();
       }

       return appData;

   }

   // example of a method to change the appData from throughout the project
   // there might be lots of there to add / remove data.

   public void addPerson(Person person) {
       Statement stmt = null;

       people.add(person); // this adds the object to the datastructures in RAM

       try {
           // Create database connection
           Connection con = DatabaseConnection.getConnection();

           // Create Statement object
           stmt = con.createStatement();

           // Create DB insert command
           String insertStatement = "INSERT INTO CONTACTS VALUES(" + "'"
                   + people.get(i).getFirstName() + "', '"
                   + people.get(i).getLastName() + "', '"
                   + people.get(i).getPhoneNumber() + "', '"
                   + people.get(i).getEmail() + "')";

           // Insert the 'insertStatement' into DB
           stmt.executeUpdate(insertStatement);

           System.out.println(people.get(i).toString()
                   + "...was saved to the database. ");

           // i is used as iterator in the people arraylist
           i++;
       } catch (SQLException e) {
           e.printStackTrace();
       }
   }

   public static Person getPerson(String firstNameOfPersonToFind,
           String lastNameOfPersonToFind) {
       Statement stmt = null;

       String firstName = null;
       String lastName = null;
       String email = null;
       String phoneNumber = null;

       try {
           // Create database connection
           Connection con = DatabaseConnection.getConnection();

           // Create Statement object
           stmt = con.createStatement();

           String getPersonQuery = "SELECT FIRST_NAME, LAST_NAME, PHONE_NUMBER, EMAIL_ADDRESS FROM CONTACTS where FIRST_NAME = '"
                   + firstNameOfPersonToFind
                   + "' AND LAST_NAME = '"
                   + lastNameOfPersonToFind + "'";

           ResultSet rs = stmt.executeQuery(getPersonQuery);
           firstName = rs.getString("FIRST_NAME");
           lastName = rs.getString("LAST_NAME");
           email = rs.getString("EMAIL_ADDRESS");
           phoneNumber = rs.getString("PHONE_NUMBER");

       } catch (SQLException e) {
           e.printStackTrace();
       }

       return new Person(firstName, lastName, email, phoneNumber);
   }

   public static ArrayList<Object> findAllPeople() {
       Statement stmt = null;
       ArrayList<Object> allPeople = new ArrayList<Object>();
       String firstName = null;
       String lastName = null;
       String email = null;
       String phoneNumber = null;

       try {
           // Create database connection
           Connection con = DatabaseConnection.getConnection();

           // Create Statement object
           stmt = con.createStatement();

           String getAllPeopleQuery = "SELECT FIRST_NAME, LAST_NAME, PHONE_NUMBER, EMAIL_ADDRESS FROM CONTACTS";
           ResultSet rs = stmt.executeQuery(getAllPeopleQuery);

           while (rs.next()) {
               firstName = rs.getString("FIRST_NAME");
               lastName = rs.getString("LAST_NAME");
               email = rs.getString("EMAIL_ADDRESS");
               phoneNumber = rs.getString("PHONE_NUMBER");

               allPeople.add(new Person(firstName, lastName, phoneNumber,
                       email));
           }

       } catch (SQLException e) {
           e.printStackTrace();
       }

       return allPeople;
   }

   public static void deletePerson(String firstNameOfPersonToDelete,
           String lastNameofPersonToDelete) {
       Statement stmt = null;

       try {
           // Create database connection
           Connection con = DatabaseConnection.getConnection();

           // Create Statement object
           stmt = con.createStatement();

           // Get info about the person we're about to delete
           String getPersonQuery = "SELECT FIRST_NAME, LAST_NAME, PHONE_NUMBER, EMAIL_ADDRESS FROM CONTACTS WHERE FIRST_NAME = '"
                   + firstNameOfPersonToDelete
                   + "' AND LAST_NAME = '"
                   + lastNameofPersonToDelete + "'";
           ResultSet rs = stmt.executeQuery(getPersonQuery);

           String firstName = rs.getString("FIRST_NAME");
           String lastName = rs.getString("LAST_NAME");
           String email = rs.getString("EMAIL_ADDRESS");
           String phoneNumber = rs.getString("PHONE_NUMBER");

           String deletePersonStatement = "DELETE FROM CONTACTS WHERE FIRST_NAME = '"
                   + firstNameOfPersonToDelete
                   + "' AND LAST_NAME = '"
                   + lastNameofPersonToDelete + "'";
           stmt.executeUpdate(deletePersonStatement);

           System.out.println("The following record was deleted: "
                   + firstName + " " + lastName + " " + phoneNumber + " "
                   + email);
           System.out
                   .println(" The database contains the following records: ");

           ArrayList<Object> myPeople = AppData.findAllPeople();

           for (Object element : myPeople) {
               System.out.println(element.toString());
           }

       } catch (SQLException e) {
           System.out.println("Error: The person: ""
                   + firstNameOfPersonToDelete + " "
                   + lastNameofPersonToDelete
                   + "" was not found. No records were deleted.");
           System.out
                   .println(" The database contains the following records: ");
           ArrayList<Object> myPeople = AppData.findAllPeople();

           for (Object element : myPeople) {
               System.out.println(element.toString());
           }
       }
   }

}

DatabaseConnection.java

package datalayer;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DatabaseConnection {

   private static Connection con;

   public static void createDatabase() {
       try {
           // Establish/create database connection
           con = DriverManager.getConnection("jdbc:sqlite:CONTACTLIST.db");
          
           Statement stmt = con.createStatement();
          
           // Create a table
           String setUpTable = "CREATE TABLE CONTACTS"
                   + "(FIRST_NAME TEXT NOT NULL, "
                   + " LAST_NAME TEXT NOT NULL, "
                   + " PHONE_NUMBER TEXT NOT NULL, "
                   + " EMAIL_ADDRESS TEXT)";

           // Execute query. Returns an integer representing the number of rows
           // affected by the SQL statement.
           stmt.executeUpdate(setUpTable);

           // Close open Statement resources
           stmt.close();

           // Releases this Connection object's database and JDBC resources
           // immediately instead of waiting for them to be automatically
           // released.
           con.close();

           System.out.println("No database file was found. Created new empty database. ");
       } catch (Exception e) {
           System.err.println(e.getClass().getName() + ": " + e.getMessage());
           System.exit(0);
       }
   }

   public static Connection getConnection() throws SQLException {

       try {
           // Load JDBC driver
           Class.forName("org.sqlite.JDBC");
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }

       File file = new File("CONTACTLIST.db");

       // Determine whether the database file exists.
       if (!file.exists()) {
           createDatabase();
       }

       if (con == null || con.isClosed()) {
           con = magicallyCreateNewConnection();
       }
       return con;
   }

   private static Connection magicallyCreateNewConnection() {
       Connection con = null;

       try {
           // Create database connection
           con = DriverManager.getConnection("jdbc:sqlite:CONTACTLIST.db");
       } catch (SQLException e) {
           e.printStackTrace();
       }

       return con;

   }
}

MainGUI.java

package userinterface;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;

import businesslayer.AppData;
import businesslayer.Person;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MainGUI extends JDialog {

   public static void main(String[] args) {
       new MainGUI().setVisible(true);
   }

   private final JPanel contentPanel = new JPanel();
   private JTextField firstName_textField;
   private JTextField lastName_textField;
   private JTextField phone_textField;
   private JTextField email_textField;

   /**
   * Create the dialog.
   */
   public MainGUI() {
       setBounds(100, 100, 226, 254);
       getContentPane().setLayout(new BorderLayout());
       contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
       getContentPane().add(contentPanel, BorderLayout.CENTER);
       contentPanel.setLayout(null);

       JLabel lblNewLabel = new JLabel("First name:");
       lblNewLabel.setBounds(28, 21, 93, 14);
       contentPanel.add(lblNewLabel);

       JLabel lblLastName = new JLabel("Last name:");
       lblLastName.setBounds(28, 52, 104, 14);
       contentPanel.add(lblLastName);

       JLabel lblNewLabel_1 = new JLabel("Email:");
       lblNewLabel_1.setBounds(28, 114, 61, 14);
       contentPanel.add(lblNewLabel_1);

       JLabel lblPhone = new JLabel("Phone:");
       lblPhone.setBounds(28, 83, 61, 14);
       contentPanel.add(lblPhone);

       firstName_textField = new JTextField();
       firstName_textField.setBounds(106, 18, 86, 20);
       contentPanel.add(firstName_textField);
       firstName_textField.setColumns(10);

       lastName_textField = new JTextField();
       lastName_textField.setColumns(10);
       lastName_textField.setBounds(106, 49, 86, 20);
       contentPanel.add(lastName_textField);

       phone_textField = new JTextField();
       phone_textField.setBounds(106, 80, 86, 20);
       contentPanel.add(phone_textField);
       phone_textField.setColumns(10);

       email_textField = new JTextField();
       email_textField.setBounds(106, 111, 86, 20);
       contentPanel.add(email_textField);
       email_textField.setColumns(10);

       JButton btnClearFields = new JButton("Clear fields");
       btnClearFields.addMouseListener(new MouseAdapter() {
           @Override
           public void mouseClicked(MouseEvent e) {
               firstName_textField.setText("");
               lastName_textField.setText("");
               phone_textField.setText("");
               email_textField.setText("");
           }
       });
       btnClearFields.setBounds(86, 149, 114, 23);
       contentPanel.add(btnClearFields);

       {
           JPanel buttonPane = new JPanel();
           buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
           getContentPane().add(buttonPane, BorderLayout.SOUTH);
           {
               JButton okButton = new JButton("OK");
               okButton.addMouseListener(new MouseAdapter() {
                   @Override
                   public void mouseClicked(MouseEvent e) {

                       AppData.getAppData().addPerson(
                               new Person(firstName_textField.getText(),
                                       lastName_textField.getText(),
                                       phone_textField.getText(),
                                       email_textField.getText()));

                       // clear text field input
                       firstName_textField.setText("");
                       lastName_textField.setText("");
                       phone_textField.setText("");
                       email_textField.setText("");
                   }
               });
               okButton.setActionCommand("OK");
               buttonPane.add(okButton);
               getRootPane().setDefaultButton(okButton);
           }
           {
               JButton cancelButton = new JButton("Cancel");
               cancelButton.addMouseListener(new MouseAdapter() {
                   @Override
                   public void mouseClicked(MouseEvent e) {
                       System.exit(0);
                   }
               });
               cancelButton.setActionCommand("Cancel");
               buttonPane.add(cancelButton);
           }
       }
   }
}