Dabbling in Android: Editing, Saving, Loading and Deleting Text (Part IIa: Classes, Constructors and Methods)


Every Android project is born with a MainActivity file or equivalent and here you will find the lifecycle methods. The initial one being: onCreate(). But I'm going to ask you to ignore this file for the moment as we continue this tutorial series and instead create a brand new class.

Our class

First of all we need to create a new class file inside our Android Studio project from last time. The easiest way to do this is to:
  1. right-click on the src->main->java->com.[your_company_name].[your_app_name] folder and select the top option (Java Class)
  2. for the purposes of this tutorial call the file "FileManagement"
You should now have a file with a class declaration that looks like this:
public class FileManagement {

}
This class will handle the creation of files along with the writing, loading and deleting of them. (Of course at the moment it does nothing!)

Constructor

Since this class will manage files it needs to know where to save them and so it needs a path to the app's file directory. The actual path will be supplied by MainActivity (in a future part of this series), our current class simply needs to store a way to access the file directory.
public class FileManagement {

    private File directory;

    public FileManagement(File directory){
        this.directory = directory;
    }
}
What I've done here is to declare a private property called directory of type File to fulfil the required task.

Note: a file isn't a physical file, it is an object for accessing, creating and deleting a file or directory at a set path.

Being assertive

Next, in the code immediately above, I've used a constructor (identified by the fact that the "method" name is identical to the class name and has no return type) to set the value of directory. Now whenever a FileManagement instance is created it will be passed what we hope is a directory. In fact if we're not passed a directory then we may as well crash the app by adding an assert method like this
public class FileManagement {

    private File directory;

    public FileManagement(File directory){
        Assert.assertTrue(directory.isDirectory()); // if constructor is not passed a directory then app will crash
        this.directory = directory;
    }
}
otherwise everything will not work as expected.

Note: at this stage you might see words (namely File and Assert) being highlighted in red and red lightbulbs appearing in Android Studio. This will be because you haven't imported the classes that we're utilising. To fix this click on the red highlighted class names and then hold down the Alt (Option) key and press Return. The compiler will either fix automatically or provide a pop-up list of options from which you should choose to import the given class. Please remember to do this throughout the tutorial whenever you see a word highlighted in red.

File creation method

Now our class knows where it will save a file, now it is time to provide the methods that will do this work. First of all is the file creation method.
public void fileCreate(String filename) throws IOException {
        File f = new File(directory, filename);
        if (f.exists()) {
            System.out.println("Status: File Already Exists");
        }
        else {
            f.createNewFile();
        }
}
This method first of all checks for the existence of the file of the name supplied within the app directory. If it does exist it will print a message to the log (LogCat) and do nothing else. Otherwise it will create the file. Finally, we use the "throws IOException" addition to our method to save writing a try and catch statement.
public void fileCreate(String filename) throws IOException {
        File f = new File(directory, filename);
        if (f.exists()) {
            System.out.println("Status: File Already Exists");
        }
        else {
            f.createNewFile();
            if (f.exists()) {
                System.out.println("Status: File Newly Created");
            }
            else {
                System.out.println("Status: File Creation Failed!");
            }
        }
    }
A try and catch statement would warn us if the file failed to be created but instead what I'm going to do is add in a simple check for the file's existence after our attempt at creating it. And because we'll be keeping a close eye on the log, I'll save try and catch for another time.

Next time

Let's take a breather here. There's lots to understand already and I don't want to overwhelm with an excess of code and ideas. Next time I'll complete the FileManagement class with the writing, (re)loading and deletion methods.


Comments