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

Shankar Madeshvaran
Nov 20, 2019 · 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.

Image for post
Image for post
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

  • The Model-View-ViewModel (MVVM) pattern helps to cleanly separate the business and presentation logic of an application from its user interface (UI).
  • 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.
Image for post
Image for post
MVVM — Flow Diagram
  • Open Visual Studio and Click on New button
Image for post
Image for post
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
Image for post
Image for post
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
Image for post
Image for post
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
Image for post
Image for post
  • Open Visual Studio and Click on Create a new project button
Image for post
Image for post
Template Choosing Page
  • Choose Mobile App(Xamarin Forms) and then click Next button.
Image for post
Image for post
Configuring New Project name and Location
  • Enter your project name and location where you want to store your project files and then click Create
Image for post
Image for post
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
Image for post
Image for post
Add NuGet Package
  • Right-click on the Solution Folder and Choose Manage NuGet Package
Image for post
Image for post
NuGet packages
  • Search for sqlite-net-pcl package and Click Add Package button
  • Add the SQLite package to all the 3 projects
  • Create a new Folder named Persistence in All of the projects
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
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
Image for post
Image for post
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 new folder named Models in ContactsBook project Solution
  • 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
  • The MVVM architectural pattern was invented with XAML in mind. The pattern enforces a separation between three software layers — the XAML user interface called the View; the underlying data called the Model; and an intermediary between the View and the Model, called the ViewModel.
  • 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
  • Navigation logic can reside in a view’s code-behind, or in a data-bound view model.
  • 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 CRUD Operation of 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
  • We need to create a View Page to design the UI, So add a new File named ContactsPage
  • 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
  • The commanding interface provides an alternative approach to implementing commands that is much better suited to the MVVM architecture.
  • 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
  • We need to create a View Model for ContactsPage, we will implement all the do all the actions and functions in View Model page Only.
  • 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.
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
  • Add a new Form named ContactsDetailPage, in ContactsDetailsPage.xaml design an UI 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.
  • As I did in previous Page View, we will add a new file named ContactsDetailViewModel
  • 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
  • The Xamarin.Forms MessagingCenter class implements the publish-subscribe pattern, allowing message-based communication between components that are inconvenient to link by object and type references.
  • 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:
Image for post
Image for post
  • 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.
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

  • Find the detailed ScreenShots and project code in this Github link. You can refer to it in case you have any queries.
  • The Project is Updated for Visual Studio 8.3

Conclusion

  • Now you know how to work with SQLite DB in Xamarin Forms.
  • Now Build and run the project, you will the screen as the below image:
Image for post
Image for post
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!

You can find me on Twitter | LinkedIn | GitHub

The Startup

Medium's largest active publication, followed by +754K 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 +754K 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 +754K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store