Technology Servants

  • Increase font size
  • Default font size
  • Decrease font size
Home Articles Shopping List - an iPhone SQLITE tutorial Part 2

Shopping List - an iPhone SQLITE tutorial Part 2


Introduction

Add View ScreenThis is the second in a series of articles on programming the iPhone / iPod Touch.  In the first article we created a shopping list with minimal functionality.  The user could display a shopping list and toggle the "needed" status of the entries.  In this article, we will learn how to start making changes to the list.  If you haven't done it yet, you should read the first article of this series.

In this version of the application, the user will be able to add new items to the shopping list.  We will also add the methods needed to change or delete items, but we won't develop the views necessary to make those changes until a future article.

The basic work flow is that when the app is first loaded, the root view displays the shopping list in a table view. If the user clicks on the Add button, the root view is replaced by the Add View screen, which allows the user to enter the information about a new item.  If the user clicks on the Save button, the new item is saved in the database and the shopping list is refreshed by reading the database again.

Code Changes

We will start by writing some new functions to make those changes.  In the screen shots for changes, we will show the new / changed lines in context to help see where the changes are made.  You can either follow along or download the code for this tutorial.  You might notice some differences between the code from the first tutorial that isn't mentioned in this article.  Those are some housekeeping changes to remove memory leaks, etc. that weren't done the first time so as not to confuse new programmers.  Experienced programmers probably already noticed the problems and fixed them on their own.

AppDelegate Changes

 We need to add some variables to the AppDelegate class to handle the additional functionality.  Let's start out by adding variables for the new SQL statements and declare the new methods.

AppDellegate Header changes for SQL

AppDelegate Header changes for methods

Since you have added a method that takes an Item as a parameter, you will need to include Item.h at the top of the header file. After changing the header file, we need to implement the new methods.

Changes to applicationDidFinishLaunching

We need to initialize the new SQL statements.  After a statement is initialized, it will no longer be nil.

Initialize new SQL statements

 deleteItemAtIndexPath Method

We need a new method that will delete an item from the database.  Like the update method, we will get passed the index path of the item to be deleted.

deleteItemAtIndexPath MethodThe first thing we do is to get the item to be deleted from the list.  The ret variable will be used to store return codes from SQLITE functions.

The first time this method is called, the delete SQL statement will be built.  The delete statement will use the ID value to uniquely identity the item.

We will bind the ID field to the statement and then execute it.  After the deletion is made, we reset the statement, remove the item from the array, and release the memory for the deleted item. Before leaving this method, the readItems method is called to refresh the list.  You could also use the path parameter determine the location of the item to be deleted, then delete that item from the list.  You probably want to do that if you have a really long list, but for this application simply re-reading the list is easier and faster.

AppDelegate insertItem Method

We now need to write a method that will insert a new item into the database.

insertItem MethodThis method is passed an Item object that is to be inserted into the database.

The first time this method is called, the insert SQL statement is initialized.  The fields are extracted from the object and bound to the statement.  Notice that we prevent the database from having any NULL strings.  When done, the statement is executed and the statement reset.

Once the new item has been inserted into the database, we call the  readItems method to refresh the list.

 User Interface

 Create UIView Controller classNow that we have finished all the changes to the existing code, we can turn to the user interface.  We need to create a new view that we will use when the user wants to add an item to the database.  Right-click on the Classes folder and select "Add" / "New File" / "UIView Controller subclass".  Make sure the "UITableViewController subclass" is not checked but the "With XIB" box is selected. and click Next.  Name the file "AddViewController" and click on the Finish button.

This will create three files in the "Classes" folder - the .h (header) file, the .m (source code) file, and the  .xib (nib) file.  I like to drag the .xib file into the "Resources" folder, but that is up to you.

Double-click on the .xib file to bring up the User Interface Builder.  Click on "Tools / Library" to see the list of components that you can add to the view.  Create rounded text fields for Name, Need, and Notes.  Change the Keyboard field for Need to "Number Pad", and any other changes you might want (like capitalizing words for the Name field).  Click on "File's Owner and associate the IBOutlet fields to the text fields.  You will also want to set up their delegates.  The figure below illustrates what it should look like.

Add View Interface configuration

New Code

Once you are done with the Interface Builder, it is time to customize AddViewController. We will also need to make a few changes to existing code that we couldn't do until the controller was created.

Root View Controller Changes

 We will start by making changes to the Root Controller.  We didn't need many changes in the first version because the default behavior did most of what we wanted. But as soon as we add a second view, we need to add code to control which views are displayed when.

First we will make changes to the controller to handle the new view.  Basically, when the user clicks on the Add button, the Add View will be displayed.  When the user is done, the root table view will be reloaded and displayed.

Root View Controller Header

 Add View Controller Header File

We will define some class variables for the Add View Controller and a navigation controller that will handle displaying and hiding the new view.  We will also create a variable to store the AppDelegate object.  In the first version, whenever we needed to access the list of items, we obtained a pointer to the AppDelegatge object and extracted the information that we needed.  While this worked just fine, as we make more changes we will be needing that object more often, so we will define a variable for it and initialize it when the controller is loaded.

Root View Controller viewDidLoadMethod

This method is probably commented out.  We need to add controls so the user can make changes.

 Root Controller viewDidLoad method

We initialize the  new view and controllers, and get the AppDelegate object.  Next we set up a title and add the Add button.  We add a click handler called addButtonClicked.  We do this by calling alloc and then initializing the button using the standard Add button.  The target parameter indicates where the notification of a button click should be sent, and the action parameter specifies that the method addButtonClicked method should be called.

Root Controller addButtonClicked

Root Controller Add Button Clicked

This method is called when the user clicks the Add button.  The first time it is called, the Add View Controller is created, along with a navigation controller for the new view.  The navigation controller presents the Add View over top of the root view.  Modal view indicates that the user can only interact with the Add view.  Once the Add View is displayed, the user is presented with a screen where they can enter a name, quantity needed, and notes.  The view remains in control of the screen until the user clicks either the Save or Cancel button.  After the Add View is completed, it will be dismissed and the root view will be visible once again.  Before the root view appears, we want to update the table that is displayed by the root view.  We will do that in the next method.

Root Controller viewWillAppear

Root Controller ViewWill Appear

This method will  be called whenever the Root Controller View is about to be displayed.  This will happen the first time the program is loaded, and after any of the other views have finished being displayed.  When the Add button is clicked, the Add View will replace the Root View, which will remain on the screen until the user clicks on either the Save button or the Cancel button.  If the Save button is clicked, then a new item has been added to the list of items.  The add routine calls readItems to read the database and recreate the shopping list.  This is done so that the new item will be in its proper location in the list.  If the user clicks on the Edit button, they will be able to delete any number of items and possibly change some of the list entries which might affect where it appears in the list.

 AddViewController Changes

 We will now make the necessary changes to the Add View Controller.  This is the view that the user will see when they add a new item to their shopping list.

Add View Controller Header

Add View Controller Header FileWe will add some class variables to store the information needed  to describe a new item for the shopping list.  When the Add View controller is displayed, the information that the user enters into the Add View form is transferred from the form fields into the corresponding variables as defined by the interface builder IBOutlet connections.  The name and need fields are text fields, and the notes are stored in a text field.  You will want to go back into the Interface Builder to make this connection.

Add View Controller Imports

Add View Controller ImportsWe will now make changes to the source file. You will need to import header files for the various types of data we will be using within this controller.

You can try to keep track of what data types you are referencing and add imports as you need them, or you can simply add all the code you need and then try to build and run the application.  If you get any messages about some data type not being defined, check to see if you misspelled the data type or need to import its header file.

Add View Controller viewDidLoad

Add View viewDidLoad method

This method is called the first time that the Add View is displayed.  We set up the navigation bar by adding a title, and two buttons for cancel and save.  We also specify two button click handlers cancelClicked and saveClicked.  The other thing we do is set the background color for the Add View to whatever the background is for the Root View. Click handlers are called when the user clicks on the corresponding button.

Add View Controller saveClicked

Add View Controller Save Clicked MethodThis is the method called when the user clicks on the Save button.  We obtain a pointer to the AppDelegate object, which contains the actual shopping list.  We then allocate a new Item object and set the name, need, and notes fields based on the form fields.

The name and notes fields are fairly straight forward.  The text property of those form fields are assigned to the Item field.  The need field needs some additional handling.  Because the form fields are text based but the need field is an integer, we need to convert the text field into an integer.  We do this by creating a NSDecimalNumber which has a method that converts text to a decimal (floating point) number.  We then use the intValue method to assign the integer equivalent to whatever the user entered in the need field.

We then use the AppDelegate object pointer to insert the new item into the database and refresh the shopping list by calling readItems again.  Finally, we dismiss the Add View which will cause the Root View to be displayed again.

Add View Controller cancelClicked

This method is called whenever the Cancel button is clicked.  The only thing we need to do if the user canceled the add, is to dismiss the Add View which will cause the Root View to be displayed again.

Add View Controller viewWillAppear

Add View Will Appear MethodThis method is called just before the view will be displayed.  We can use this method to initialize the form fields.  If we don't do that, then whenever the user tries to add another item, the form will still have whatever the user had entered the time before.  We set the name and notes fields to an empty string, and the need field to one.

 In addition to clearing the fields, we start the Add View so that the focus and keyboard is on the name field.  This isn't really necessary, but if we don't, the user would have to click in the name field before they started to type.

Add View Controller dealloc

Add View dealloc MethodThis method is called when the view is about to be unloaded and all memory is to be released.  Every time you define some class variables in the interface of a header file, you should make sure you release them in the dealloc method.

 We release the txtName, txtNeed, and txtNotes fields, and then call the dealloc method of the super class.

 

Build and Run Application

That concludes the changes needed to add an item to the shopping list.  Build and run the application.  Try adding new items for your shopping list.  In the next version of this application, we will let the user change or delete items already in the list.

I would welcome feedback on this article.  You can either add a comment here or email me your comments.  The source files can be found on the download page for my personal web site:

http://billpringle.com/download/index.html

You can also read the next installment of this tutorial.

 

 



Add this page to your favorite Social Bookmarking websites
Reddit! Del.icio.us! Mixx! Free and Open Source Software News Google! Live! Facebook! StumbleUpon! TwitThis Joomla Free PHP
Comments (0)
Only registered users can write comments!