Get up to 80 % extra points for free! More info:

Lesson 15 - Diary with a database in Java

In the previous exercise, Solved tasks for OOP in Java lesson 12, we've practiced our knowledge from previous lessons.

In the previous lesson, Solved tasks for OOP in Java lesson 12, we learned about date and time in Java. We also know ArrayList which allows us to add new items at run-time so we don't have to worry about its size. In today's tutorial, we're going to make a program that involves storing objects in an ArrayList.

At first, I was going to have us create a user database, but we've already dealt with users several times in this course. Since we now know how to deal with dates and times, we're going to make a digital diary/journal. We'll store entries into a database and print today's and tomorrow's entries. This database won't be an "actual" database, we will cover databases later on. All it will be is an ArrayList in computer memory which will allow the user to add entries, search for them by date and remove them by specifying a date and time.

Let's create a new application and name it Journal (don't name it Diary since we'll need that name for a class).

The entry

First of all, we'll have to create a class whose instances we will store. Let's name it Entry. Diary entries will be related to a certain date and time. It will also contain text, e.g.: January 12, 2016 - Walk the dog. Our class might look something like this:

import java.time.LocalDateTime;

public class Entry {
    private LocalDateTime dateTime;
    private String text;

    public Entry(LocalDateTime dateTime, String text) {
        this.dateTime = dateTime;
        this.text = text;
    }

    public LocalDateTime getDateTime() {
        return dateTime;
    }

    public void setDateTime(LocalDateTime dateTime) {
        this.dateTime = dateTime;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    @Override
    public String toString()
    {
        return dateTime + " " + text;
    }
}

All this class is meant to do is store data, so it has no methods, other than the constructor and toString() and some getters/setters). You may noticed that the toString() method doesn't format the date anyhow. We'll get back to it later.

The database

Since our program will be a bit more complex, we'll use multiple objects to keep things nice and neat. We've already made the entry class, now let's create a Database object in which our entries will be stored. There will be a private list as there was in the Lottery application in previous lessons. The ArrayList will be of the Entry data type this time. Our diary will allow us to add, delete and search entries by date. Let's add the Database class to the project. It will be very similar to the Lottery app from previous lessons:

import java.util.ArrayList;

public class Database {
    private ArrayList<Entry> entries;

    public Database() {
        entries = new ArrayList<>();
    }

}

Notice the "diamond operator" used when creating a new ArrayList instance. Since Java 7, we don't have to specify the generic type twice, but just in the variable declaration and then we can leave the angle brackets empty. Let's also say that if we've omitted angle brackets at all and both declared and initialized the ArrayList without specifying the generic type, items would be saved as Object types. We'd have to cast them to our Entries manually. We'll learn ho would we do that later in the course and you'll also meet lists in the Java collection course.

The Entry class will only be used for data manipulation. It will contain an internal collection of entries that will be initialized in the constructor. We could also initialize it directly without a constructor in the field declaration:

private ArrayList<Entry> entries = new ArrayList<>();

Now let's add some methods that will add, delete and search an entry.

Adding an entry is very simple and straightforward:

public void addEntry(LocalDateTime dateTime, String text) {
    entries.add(new Entry(dateTime, text));
}

As for the second method, we'll allow the user to search for entries by day. The method will return the ArrayList of found entries since there could be multiple entries per day in the database. We'll be able to search for entries both by date and time or just by date. This way, we can find entries on a particular day no matter what time they occur. We'll specify our search settings using a byTime boolean parameter. If it's false, our search will be by date only. First, we'll create an ArrayList and add entries that match the given date. We'll match either full date and time if the boolean parameter is true, or just the date component of it in case the boolean parameter is false. Lastly, we'll return the list containing all related entries.

public ArrayList<Entry> findEntries(LocalDateTime dateTime, boolean byTime) {
    ArrayList<Entry> found = new ArrayList<>();
    for (Entry entry : entries) {
        if ((byTime && (entry.getDateTime().equals(dateTime))) // filtered by time and date
        ||
        ((!byTime) && (entry.getDateTime().toLocalDate().equals(dateTime.toLocalDate())))) { // filtered by date only
            found.add(entry);
        }
    }
    return found;
}

We'll finish up the class by adding a method that deletes entries based on a given time. We'll perform it using the findEntries() method, iterating over its result and removing found entries from the list. We'll be deleting entries of a specific date and time so the second parameter of the findEntries() method will be true:

public void deleteEntries(LocalDateTime dateTime) {
    ArrayList<Entry> found = findEntries(dateTime, true);
    for (Entry entry : found) {
        entries.remove(entry);
    }
}

Diary

Now let's add the last class to our project, which will represent the diary itself. We'll name it Diary to keep things simple and clear. It will include methods for interacting with the user. Notice how we divide our application and encapsulate its individual parts. The ArrayList is encapsulated in the Database class which provides various methods that help handle its contents safely. Let's create a Database instance in our diary. This way, we separate the data logic from the user communication logic, and even that from other program inputs/outputs. The Diary class is supposed to interact with the user and pass the entered data to the database.

Let's add a private Database instance and initialize it in the constructor. Let's add a Scanner instance as well since we're going to need it:

import java.util.Scanner;

public class Diary {

    private Database database;
    private Scanner scanner = new Scanner(System.in);

    public Diary() {
        database = new Database();
    }

}

We'll finish the Diary class in the next lesson, Diary with a database in Java (finishing), when we'll also finish the whole application.


 

Previous article
Solved tasks for OOP in Java lesson 12
All articles in this section
Object-Oriented Programming in Java
Skip article
(not recommended)
Diary with a database in Java (finishing)
Article has been written for you by David Capka Hartinger
Avatar
User rating:
1 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities