Xamarin.Forms MVVM: How to Work with SQLite DB(C# — Xaml)

Shankar Madeshvaran
Nov 20 · 11 min read

We are going to develop a ContactsBook App(Android & iOS) in MVVM Architecture using Xamarin Forms then learn how to do CRUD (Create, Read, Update and Delete) operation in the SQLite database.

Photo by Arian Darvishi on Unsplash

Xamarin.Forms is an open-source cross-platform framework from Microsoft for building iOS, Android, & Windows apps with .NET from a single shared codebase. Using Xamarin.Forms built-in pages, layouts, and controls we can build and design mobile apps from a single API that is highly extensible.

If you are a beginner in Xamarin Development, check out this article because I have explained in detail everything you need to know before starting Xamarin development.

In this article, we are going to develop a cross-platform application(ContactsBook) which runs in both iOS and Android Platforms.

By building ContactsBook App, we are going to learn about:

  • How to develop a real-world application in Xamarin Forms(Android and iOS)
  • What is MVVM? How to work with MVVM Architecture?
  • How to work with SQLite in Xamarin.Forms
  • How to do CRUD Operation in SQLite

Ready? Let’s go.

Building Real World Application In Xamarin Forms: MVVM

MVVM Architecure :

  • Maintaining a clean separation between application logic and the UI helps to address numerous development issues and can make an application easier to test, maintain, and evolve.
  • It can also greatly improve code re-use opportunities and allows developers and UI designers to more easily collaborate when developing their respective parts of an app.
  • There are three core components in the MVVM pattern: the model, the view, and the view model. Each serves a distinct purpose.
MVVM — Flow Diagram

Creating a New Project on MacOS

Choosing Template Screen on Visual Studio
  • Choose multiplatform so that we can build projects that can run on both iOS and Android Platform.
  • Select Blank Forms App and then click Next button
Configure Blank Forms App Page
  • Enter your project name and Organisation Identifier
  • Choose the platforms that you wish to develop your Xamarin application and click Next
Configuring App Location
  • Choosing the location that you wish to store your project
  • Add a Git Version and .gitignore file if you need
  • Add an automated UI test to the project if you need and then Click Create

Creating a New Project on Windows

  • Open Visual Studio and Click on Create a new project button
Template Choosing Page
  • Choose Mobile App(Xamarin Forms) and then click Next button.
Configuring New Project name and Location
  • Enter your project name and location where you want to store your project files and then click Create
Configure platforms and Forms Page
  • Choose Blank Form page and Choose the platforms(iOS and Android) you want to develop your app and then click OK button

Add Necessary packages (Eg: SQLite)

Add NuGet Package
  • Right-click on the Solution Folder and Choose Manage NuGet Package
NuGet packages
  • Search for sqlite-net-pcl package and Click Add Package button
  • Add the SQLite package to all the 3 projects

Configure SQLite DB for Android and iOS Projects

Creating a new Folder on All the Projects
  • For Solution Project — Right-click on the ContactBook Solution folder and then choose Add -> New Folder
  • For Android Project — Right-click on the ContactBook.Android Folder and then choose Add -> New Folder
  • For iOS Project — Right-click on the ContactBook.iOS Folder and then choose Add -> New Folder
Naming the folder Persistence
  • Add a New Filename ISQLiteDb.cs to Folder Persistence in ContactsBook Solution Folder
Creating A SQLite Connection
  • Add a New Filename SQLiteDb.cs to Folder Persistence in ContactsBook.Android Project Folder
Providing path for Storing Db in Folder in Android
  • Add a New Filename SQLiteDb.cs to Folder Persistence in ContactsBook.iOS Project Folder
Providing Path for Storing Db in Folder in iOS

Create a Model Class

  • Add a new file named Contact.cs which has details of contacts such as Id, first name, last name, phone, and email
Model Class for Contact details

Create a View Model Class :

  • The View and the ViewModel are often connected through data bindings defined in the XAML file.
  • The BindingContext for the View is usually an instance of the ViewModel.
  • By creating a View Model, this class act as an intermediary between View and Contact Model class
  1. Create a Base View Model Class
  • In the Base View Model Class, we implement INotifyPropertyChanged
  • INotifyPropertyChanged is an interface member in System.ComponentModel Namespace. This interface is used to notify the Control that property value has changed.
  • This interface is used to notify the Control that the property value has changed to the View Model.
BaseViewModel Class
  • In BaseViewModel class, we implemented propertyChanged for generic type and extend its properties for all data types.

2. Create a ViewModel Class For Contact:

  • By creating ViewModel For Contact, we provide all the necessary details need to access each contact
  • By extending the BaseViewModel class, we implement INotifyPropertyChanged for all the contacts, when the values edited or changes then the view model will be notified of the changes.
ContactViewModel Class — To get notified of any changes done to Contact

Create an Interface For Navigation

  • While placing navigation logic in a view might be the simplest approach, it is not easily testable through unit tests.
  • Placing navigation logic in view model classes means that the logic can be exercised through unit tests.
  • In addition, the view model can then implement logic to control navigation to ensure that certain business rules are enforced.
  • For example, an app might not allow the user to navigate away from a page without first ensuring that the entered data is valid.
  • The Contacts app uses the navigation class to provide view model-first navigation. This class implements the interface, which is shown in the following code example:
IPageService — This interface specifies that an implementing class must provide the above Methods
  • The class that extends the above Interface must provide all of the above methods declared. I have created and implemented the above methods in a separate class named PageService
PageService class file which implemented all the functions in IPageSevice Interface
  • DisplayAlert() — Used to display alerts based on the parameters passed
  • PushAsync() — Used to Navigate from One Page View to another Page View
  • PopAsync() — Used to Dismiss the current Page View

Create an Interface To Do Add, Read, Edit, Delete Contact Details

IContactStore.cs
  • To define the methods in IContactStore, we will extend this interface and define all the methods in view model class of Page View.
  • The class that extends the above Interface must provide all of the above methods declared. I have created and implemented the above methods in a separate class named SQLiteContactStore
SQLiteContactStore file which implemented all the functions in IContactStore Interface
  • GetContactsAsync() — Convert contacts stored in SQLite database to List
  • DeleteContact() — Delete contact from SQLite database
  • AddContact() — Add contact to SQLite database
  • UpdateContact() — Update the edited contact details in SQLite database
  • GetContact() — Return a contact detail by using Id

Create a View Page(Add, Read, Delete Contact):

  • In ContactsPage , we develop a design to Add, Read and Delete Contacts
ContactsPage Xaml — Page to Designing a UI
  • In this ContactsPage.xaml , I have used Interface and parameters such as Command, CommandParameter and Binding

Command and CommandParameter Property

  • The ViewModel itself can contain commands, which are methods that are executed in reaction to a specific activity in the View such as a Button click.
  • Data bindings are defined between these commands and the Button.
  • To allow a data binding between a Button and a ViewModel, the Button defines two properties:
  • Command of type System.Windows.Input.ICommand
  • CommandParameter of type Object
  • To use the command interface, you define a data binding that targets the Command property of the Button where the source is a property in the ViewModel of type ICommand.
  • The ViewModel contains code associated with that ICommand property that is executed when the button is clicked. You can set CommandParameter to arbitrary data to distinguish between multiple buttons if they are all bound to the same ICommand property in the ViewModel.

The Command and CommandParameter properties are also defined by the following classes:

  • MenuItem and hence, ToolbarItem, which derives from MenuItem
  • TextCell and hence, ImageCell, which derives from TextCell

Create a View Model for ContactsPage:

  • The View and the ViewModel are often connected through data bindings defined in the XAML file.
ContactsPageViewModel — View Model class For ContactsPage
  • When LoadDataCommand is triggered when view is loaded, it will call LoadData() where it will load all the contacts stored in SQLite Db.
  • When SelectContactCommand() is triggered by selecting an Item in ListView, it will call SelectContact() where it will navigate to ContactDetailPage to edit the selected contact details and save the changes in SQLite DB.
  • When AddContactCommand() is triggered by click on the Add button in Toolbar, it will call AddContact() where it will navigate to New page named ContactDetailPage, to add new contact details
  • When DeleteContactCommand() is triggered by clicking a Menu Item in ListView, it will call DeleteContact() where it will remove the contact detail in SQlite and ListView.
  • When CallContactCommand() is triggered by clicking a Menu Item in ListView, it will call CallContact() where it will make the call to using the particular contact’s mobile number.

Assigning instances of View Model to ContactsPage

ContactsPage.xaml.cs
  • The BindingContext for the View is usually an instance of the ViewModel.
  • By assigning a ContactsViewModel instances to ContactsPage.xaml.cs, every command action that triggers in ContactsPage.xaml is called in the view model

Create a New Page View(ContactsDetailPage) To Add and Edit Contact Details:

ContactsDetailPage.xaml — Designing UI To Add and Edit Contact Details
  • TableView is a view for displaying scrollable lists of data or choices where there are rows that don't share the same template. Unlike ListView, TableView does not have the concept of an ItemsSource, so items must be manually added as children.
  • Elements in a TableView are organized into sections. At the root of the TableView is the TableRoot, which is a parent to one or more TableSection instances.
  • EntryCell is useful when you need to display text data that the user can edit.
  • EntryCell also exposes the Completed event, which is fired when the user hits the 'done' button on the keyboard while editing text.
  • SwitchCell is the control to use for presenting and capturing an on/off or true/false state.
  • SwitchCell also exposes the OnChanged event, allowing you to respond to changes in the cell's state.
  • When the built-in cells aren’t enough, custom cells can be used to present and capture data in a way that makes sense for your app.
  • All custom cells must derive from ViewCell, the same base class that all of the built-in cell types use. I have created a custom cell by providing Button inside of View Cell.
  • All of these properties are bindable.

Create a View Model for ContactsDetailPage:

  • We will define all the actions and functions inside this view model only and we will achieve this by assigning this class instance in BindingContext of the ContactsDetailPage
ContactsDetailViewModel — View Model class For ContactsDetailPage
  • When SaveCommand() is triggered by a click on the Save button, it will call Save() methods which will trigger function ContactAdded or ContactUpdated based on the Id.
  • Id value is zero when a new contact is added and the value of Id value won’t be zero when the contact details parameter is passed from ContactsPage.
  • Based on Id value MessaginCenter will call ContactAdded or ContactUpdated by using the string(Event.ContactAdded or Event.ContactUpdated)
  • MessagingCenter messages are strings. Publishers notify subscribers of a message with one of the MessagingCenter.Send overloads.
Events — MessagingCenter String Messages

Messaging Center

  • This mechanism allows publishers and subscribers to communicate without having a reference to each other, helping to reduce dependencies between them.
  • The MessagingCenter class provides multicast publish-subscribe functionality.
  • This means that there can be multiple publishers that publish a single message, and there can be multiple subscribers listening for the same message:
  • Publishers send messages using the MessagingCenter.Send method, while subscribers listen for messages using the MessagingCenter.Subscribe method.
  • In addition, subscribers can also unsubscribe from message subscriptions, if required, with the MessagingCenter.Unsubscribe method.
  • Subscribers can register to receive a message using one of the MessagingCenter.Subscribe overloads. The following code example shows an example of this:
ContactsPageViewModel() — Defining Messaging Center Functions
  • Implement the messaging center functions in ContactsPageViewModel.cs
  • When Event.ContactAdded or Event.ContactUpdated is send from ContactsDetailPage, the subscriber will receive it and call the respective functions.

Assigning instances of ContactsDetailViewModel to ContactsDetailPage

ContactsDetailPage.xaml.cs — Assiging instance of view model to binding context
  • The BindingContext for the View is usually an instance of the ViewModel.
  • By assigning a ContactsDetailViewModel instances to ContactsDetailPage.xaml.cs , every command action that triggers in ContactsDetailPage.xaml is called in view model.

Resources

  • The Project is Updated for Visual Studio 8.3

Conclusion

  • Now Build and run the project, you will the screen as the below image:
ScreenShots

I hope you found this article helpful. If you did, please don’t hesitate to clap or share this post on Twitter or your social media of choice, every share helps me to write more. If you have any queries, feel free to comment below and I’ll see what I can do. Thanks.

Let’s connect!

The Startup

Medium's largest active publication, followed by +538K people. Follow to join our community.

Shankar Madeshvaran

Written by

iOS and Xamarin Developer.I love to write articles regarding Techs,iOS and Xamarin concepts. Follow me on GitHub: https://github.com/shankarmadeshvaran

The Startup

Medium's largest active publication, followed by +538K people. Follow to join our community.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade