52 Weeks of Xamarin: Week 16 – Creating an iOS Application Part 2

Last week we began creating an iOS application. ToDoList
 We covered most of what is required but we did not tackle persistence, which we will do today.

This post is based on my Pluralsight course Beginning Mobile Development with Xamarin.

We begin by adding a package to our project: Sqlite-net.

When you search for SQLite in Nuget you’ll find there are a number of similarly named packages. The one you want has a dash and a single author, Frank Krueger.

NuGetSqlite

This will add the package as well as a couple files to your project (SQLite.cs and SQLiteAsync.cs).

We’ll need a ToDoItem class to simplify adding and retrieving ToDo items.  That class will have an ID property specifically for the database, and will be attributed accordingly.

 public class ToDoItem {   
     [PrimaryKeyAttribute, AutoIncrement]
     public int ID { get; set; }
     public string TaskName { get; set; }
     public string Priority { get; set; }
     public string DueDate { get; set; }
     public bool IsDeleted { get; set; }   
 } 

SQLite Setup

Turn to the ViewController and add a SQLite.SqliteConnection named database, and an object named locker.

public partial class ViewController : UIViewController {
    private SQLite.SQLiteConnection database;
    static object locker = new object();

  The next task is to set the connection.  Normally, we’d use a path on the phone, but for now we’ll use a local path to make working with the database easier.  We set the path and use that to obtain a connection object,

public void SetConnection(){
    var path = /users/jesseliberty/Data/ToDo.db;
    var conn = new SQLite.SQLiteConnection(path);
    conn.CreateTable<ToDoItem>();
    database = conn;
}

Now we are ready to implement the event handler

SaveButton.TouchUpInside += (sender, e) => {
     var toDoItem = new ToDoItem();
     toDoItem.TaskName = TaskName.Text;
     database.Insert(toDoItem);
 }

Turning to ToDoReviewController, at the top of the method, add these lines:

         public List<ToDoItem> ToDoItems { get; set; }
         static NSString toDoReviewCellId = 
             new NSString("ToDoReviewCell");

Now we can implement the constructor where we first register the class for cell reuse, allowing the most efficient implementation of the table.  
 public ToDoReviewController(IntPtr handle)
     : base(handle) {
     TableView.RegisterClassForCellReuse(
         typeof(UITableViewCell),
         toDoReviewCellId);
     TableView.Source = new ToDoReviewDataSource(this);
     ToDoItems = new List<ToDoItem>();
     var conn = new SQLite.SQLiteConnection(
                    "/users/jesseliberty/data/ToDo.db");
     var query = conn.Table<ToDoItem>();
     foreach (ToDoItem toDoItem in query) {
         ToDoItems.Add(toDoItem);
     }
 
 }
 

All that is left is to implement an internal class: ToDoReviewDataSource that derives from UITableViewSource,

class ToDoReviewDataSource : UITableViewSource {

    ToDoReviewController controller;

    public ToDoReviewDataSource(ToDoReviewController controller) {
        this.controller = controller;
    }

    public override nint RowsInSection(UITableView tableview, 
        nint section) {
        return controller.ToDoItems.Count;
    }

    public override UITableViewCell GetCell(UITableView tableView, 
        NSIndexPath indexPath) {
        var cell = tableView.DequeueReusableCell(
            ToDoReviewController.toDoReviewCellId);
        int row = indexPath.Row;
        cell.TextLabel.Text = controller.ToDoItems[row].TaskName;
        return cell;
    }

}

Double check that you have a link between the Root View Controller’s Review button and the TableViewController.  Fill in a few ToDo items, saving each and then click review to see them listed.  Close and re-open the project and click review; the items are still there as they have been persisted in the database.

To cap things off, obtain the (free) utility sqlitebrowser and click OpenDatabase.  Navigate to your database and click Open.  The structure of your database is displayed and if you click Browse data you can see your tables and the data within.

dbtool

The ToDoItem class includes a number of additional fields.  Retrieving, storing and viewing that data is left as a useful exercise.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Xamarin. Bookmark the permalink.

4 Responses to 52 Weeks of Xamarin: Week 16 – Creating an iOS Application Part 2

Comments are closed.