Introduction:
This article will show you step by step guide on how to use an SQLite database with a Xamarin.Forms application in Android and iOS.
Requirements:
- This article source code is prepared by using Visual Studio Community for Mac (7.4). And it is better to install latest visual studio updates from here.
- This sample project is Xamarin.Forms PCL project and tested in Android emulator and iOS simulators.
- Storage: Used SQLite.Net-PCL Nuget package version is 3.1.1
- Validation: Used FluentValidation Nuget Package version is V7.5.2.
Description:
In this article we will take a sample that would helpful to understand SQLite operations in Xamarin.Forms and sample project will have below functionality.
- Add Contact (AddContact, AddContactViewModel): Insert new contact details to SQLite database. Also will have a option to "View All Contacts" if contacts exist in database.
- Contact List (ContactList, ContactListViewModel): Read all contacts from SQLite and displaying contact list. Also will have a option to delete all/add the contact.
- Contact Details (DetailsPage, DetailsViewModel): Read specific contact from SQLite and showing full information for the same. Also will have a option to delete/update the contact.
1. How to create Xamarin.Forms PCL project with Visual Studio for Mac?
2. How to setup SQLite and perform SQLite operations in Xamarin.Forms PCL project?
3. How to validate Contact Details with Fluent Validation before data insert?
2. How to setup SQLite and perform SQLite operations in Xamarin.Forms PCL project?
3. How to validate Contact Details with Fluent Validation before data insert?
4. How to use default MVVM to create ViewModels in Xamarin.Forms app?
5. How to bind Contact Views with ViewModels?
1. How to create Xamarin.Forms PCL project using Visual studio for Mac?
First we need to create the new Xamarin.Forms project.
- Launch Visual Studio for Mac.
- On the File menu, select New Solution.
- The New Project dialog appears. In the left pane Multiplatform > App > Xamarin.Forms > Blank Forms App and click on Next.
- Enter your App Name (Ex: SQLiteSample). Select Target Platforms to Android & iOS and Shared Code to Portable Class Library after that click on Next button.
- You can choose your project location like below and Create new project.
And project structure will be.
- SQLiteSample: It is for PCL shared code.
- SQLiteSample.Droid: It is for Android.
- SQLiteSample.iOS: It is for iOS.
2. How to setup SQLite and perform SQLite operations in Xamarin.Forms PCL project?
After creating Xamarin.Forms application, we need a managed way to access SQLite database. For that we need to add relevant nuget package name is SQLite.Net-PCL to PCL, Android & iOS projects. SQLite.Net-PCL is a .NET wrapper around SQLite that will allow us to access the native SQLite functionality from a Xamarin.Forms PCL or shared project.
So Right on your PCL project Packages and click on Add Packages.
After that Add Packages dialog window will open, search for "SQLite.Net-PCL" and click on Add Package like below.
After that above package will add to your Xamarin.PCL project like below.
Also please add above package to SQLiteSample.Droid and SQLiteSample.iOS projects by following same above steps like SQLiteSample PCL project. And make sure SQLite.Net-PCL same version package should add to Android and iOS project Packages folder like below.
We completed the SQLite setup for our xamarin forms project. So it is time to perform all SQLite(Create, Read, Update, Delete, Insert) operations. But before that even tough the "SQLite.Net-PCL" package will provide us the functionality of manipulating the SQLite database, it can’t automatically initialize the database connection object as the location of the database file varies on different platforms. So in order to solve this issue we will use dependency service to load the database file in connection object and please follow below few steps.
Step 1: Create Interface (ISQLite) in PCL.
We are following default MVVM design pattern. And here we will place helpers in Helpers folder. So right click on your project name SQLiteSample => Add => New Folder name is "Helpers". After that right click on your newly created the folder => Add => New File => General => Empty Interface and name it ISQLite and add below code:
Step 2: Android Implementation for ISQLite.
In SQLiteSample.Droid project, create folder "Implementations" and create class "AndroidSQLite". After that add below code:
- using System.IO;
- using SQLite.Net;
- using SQLiteSample.Droid.Implementaions;
- using SQLiteSample.Helpers;
- [assembly: Xamarin.Forms.Dependency(typeof(AndroidSQLite))]
- namespace SQLiteSample.Droid.Implementations {
- public class AndroidSQLite : ISQLite {
- public SQLiteConnection GetConnection() {
- string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
- // Documents folder
- var path = Path.Combine(documentsPath, DatabaseHelper.DbFileName);
- var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
- var conn = new SQLiteConnection(plat, path);
- // Return the database connection
- return conn;
- }
- }
- }
Step 3: iOS Implementation for ISQLite.
In SQLiteSample.iOS project, create folder "Implementations" and create class "iOSSQLite". After that add below code:
- using System;
- using System.IO;
- using Xamarin.Forms;
- using SQLite.Net;
- using SQLiteSample.Helpers;
- using SQLiteSample.iOS.Implementaions;
- [assembly: Dependency(typeof(IOSSQLite))]
- namespace SQLiteSample.iOS.Implementations {
- public class IOSSQLite : ISQLite {
- public SQLiteConnection GetConnection() {
- string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
- string libraryPath = Path.Combine(documentsPath, "..", "Library"); // Library folder
- var path = Path.Combine(libraryPath, DatabaseHelper.DbFileName);
- // Create the connection
- var plat = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS();
- var conn = new SQLiteConnection(plat, path);
- // Return the database connection
- return conn;
- }
- }
- }
Step 4: Performing SQLite operations with Database Helper class in PCL
In SQLiteSample PCL project, create a class in Helpers folder that should have methods to perform SQLite operation (create, insert, delete, read, update).
- using SQLite.Net;
- using Xamarin.Forms;
- using System.Collections.Generic;
- using System.Linq;
- using SQLiteSample.Models;
- using System;
- namespace SQLiteSample.Helpers {
- public class DatabaseHelper {
- static SQLiteConnection sqliteconnection;
- public const string DbFileName = "Contacts.db";
- public DatabaseHelper() {
- sqliteconnection = DependencyService.Get<ISQLite>().GetConnection();
- sqliteconnection.CreateTable<ContactInfo>();
- }
- // Get All Contact data
- public List<ContactInfo> GetAllContactsData() {
- return (from data in sqliteconnection.Table<ContactInfo>()
- select data).ToList();
- }
- //Get Specific Contact data
- public ContactInfo GetContactData(int id) {
- return sqliteconnection.Table<ContactInfo>().FirstOrDefault(t => t.Id == id);
- }
- // Delete all Contacts Data
- public void DeleteAllContacts() {
- sqliteconnection.DeleteAll<ContactInfo>();
- }
- // Delete Specific Contact
- public void DeleteContact(int id) {
- sqliteconnection.Delete<ContactInfo>(id);
- }
- // Insert new Contact to DB
- public void InsertContact(ContactInfo contact) {
- sqliteconnection.Insert(contact);
- }
- // Update Contact Data
- public void UpdateContact(ContactInfo contact) {
- sqliteconnection.Update(contact);
- }
- }
- }
In above SQLite helper class, we created queries for ContactInfo Table means that we need to create ContactInfo class that should have columns.
So create Models folder in PCL and add below Table class.
- using System;
- using SQLite.Net.Attributes;
- namespace SQLiteSample.Models
- {
- [Table("ContactInfo")]
- public class ContactInfo
- {
- [PrimaryKey, AutoIncrement]
- public int Id { get; set; }
- public string Name { get; set; }
- public string Age { get; set; }
- public string Gender { get; set; }
- public DateTime DOB { get; set; }
- public string Address { get; set; }
- public string MobileNumber { get; set; }
- }
- }
Please note that in above class, Id property is marked as the Primary Key and AutoIncrement which will helpful for contact row identification.
Step 5: Create interface for ContactInfo Table operations
We will create service that will talk to only ContactInfo Table. So create Services folder in PCL and add below IContactRepository interface
- using System;
- using System.Collections.Generic;
- using SQLiteSample.Models;
- namespace SQLiteSample.Servcies
- {
- public interface IContactRepository
- {
- List<ContactInfo> GetAllContactsData();
- //Get Specific Contact data
- ContactInfo GetContactData(int contactID);
- // Delete all Contacts Data
- void DeleteAllContacts();
- // Delete Specific Contact
- void DeleteContact(int contactID);
- // Insert new Contact to DB
- void InsertContact(ContactInfo contact);
- // Update Contact Data
- void UpdateContact(ContactInfo contact);
- }
- }
And after that create a class that should implement above interface.
- using System.Collections.Generic;
- using SQLiteSample.Helpers;
- using SQLiteSample.Models;
- namespace SQLiteSample.Servcies
- {
- public class ContactRepository : IContactRepository
- {
- DatabaseHelper _databaseHelper;
- public ContactRepository(){
- _databaseHelper = new DatabaseHelper();
- }
- public void DeleteContact(int contactID)
- {
- _databaseHelper.DeleteContact(contactID);
- }
- public void DeleteAllContacts()
- {
- _databaseHelper.DeleteAllContacts();
- }
- public List<ContactInfo> GetAllContactsData()
- {
- return _databaseHelper.GetAllContactsData();
- }
- public ContactInfo GetContactData(int contactID)
- {
- return _databaseHelper.GetContactData(contactID);
- }
- public void InsertContact(ContactInfo contact)
- {
- _databaseHelper.InsertContact(contact);
- }
- public void UpdateContact(ContactInfo contact)
- {
- _databaseHelper.UpdateContact(contact);
- }
- }
- }
3. How to validate Contact Details with Fluent Validation?
It will be always good to validate details before save them to database. In this article we are validating ContactInfo table information before inserting into SQLite. Please read to understand how to validate particular class object with FluentValidation from this article.
In SQLiteSample PCL project, we have to add ContactValidator class in Validator folder.
- using FluentValidation;
- using SQLiteSample.Models;
- namespace SQLiteSample.Validator
- {
- public class ContactValidator : AbstractValidator<ContactInfo>
- {
- public ContactValidator()
- {
- RuleFor(c => c.Name).Must(n=>ValidateStringEmpty(n)).WithMessage("Contact name should not be empty.");
- RuleFor(c => c.MobileNumber).NotNull().Length(10);
- RuleFor(c => c.Age).Must(a => ValidateStringEmpty(a)).WithMessage("Contact Age should not be empty.");
- RuleFor(c => c.Gender).Must(g => ValidateStringEmpty(g)).WithMessage("Contact Gender should not be empty.");
- RuleFor(c => c.DOB).Must(d => ValidateStringEmpty(d.ToString())).WithMessage("Contact DOB should not be empty.");
- RuleFor(c => c.Address).Must(a => ValidateStringEmpty(a)).WithMessage("Contact Adress should not be empty.");
- }
- bool ValidateStringEmpty(string stringValue){
- if (!string.IsNullOrEmpty(stringValue))
- return true;
- return false;
- }
- }
- }
4. How to use default MVVM to create ViewModels in Xamarin.Forms app?
It is best practices to write business logic in view models before start to build views user interface. And we are adding functionality for the view models below.
- AddContactViewModel: Saving new contact details in database.
- ContactListViewModel: Read all contacts from database.
- DetailsViewModel: Read specific contact from database and delete/update same contact.
Let's start write business logic to viewmodels
AddContactViewModel
Above UI screen is for AddContactView. So ViewModel should have below properties and commands.
Properties: Name, Mobile Number, Age, Gender, DOB, Address. And these properties will be the same for Contact DetailsViewModel. So we will add these properties into common view model name is BaseContactViewModel.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Runtime.CompilerServices;
- using FluentValidation;
- using SQLiteSample.Helpers;
- using SQLiteSample.Models;
- using SQLiteSample.Servcies;
- using Xamarin.Forms;
- namespace SQLiteSample.ViewModels
- {
- public class BaseContactViewModel : INotifyPropertyChanged {
- public ContactInfo _contact;
- public INavigation _navigation;
- public IValidator _contactValidator;
- public IContactRepository _contactRepository;
- public string Name
- {
- get => _contact.Name;
- set{
- _contact.Name = value;
- NotifyPropertyChanged("Name");
- }
- }
- public string MobileNumber
- {
- get => _contact.MobileNumber;
- set {
- _contact.MobileNumber = value;
- NotifyPropertyChanged("MobileNumber");
- }
- }
- public string Age
- {
- get => _contact.Age;
- set {
- _contact.Age = value;
- NotifyPropertyChanged("Age");
- }
- }
- public string Gender
- {
- get => _contact.Gender;
- set {
- _contact.Gender = value;
- NotifyPropertyChanged("Gender");
- }
- }
- public DateTime DOB
- {
- get => _contact.DOB;
- set {
- _contact.DOB = value;
- NotifyPropertyChanged("DOB");
- }
- }
- public string Address
- {
- get => _contact.Address;
- set {
- _contact.Address = value;
- NotifyPropertyChanged("Address");
- }
- }
- List<ContactInfo> _contactList;
- public List<ContactInfo> ContactList
- {
- get => _contactList;
- set
- {
- _contactList = value;
- NotifyPropertyChanged("ContactList");
- }
- }
- #region INotifyPropertyChanged
- public event PropertyChangedEventHandler PropertyChanged;
- protected void NotifyPropertyChanged([CallerMemberName] string propertyName = ""){
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
- }
- #endregion
- }
- }
In above BaseContactViewModel, we also added below common interfaces
- INavigation: For page navigation
- IValidator: To validae contact object.
- IContactRepository: To access ContactInfo Table operations.
Commands:
- AddContactCommand(for Save Contact Button click)
- ViewAllContactsCommand (View All Contacts Label tap).
So create ViewModels folder in PCL project and add below AddContactViewModel class.
- using System.Threading.Tasks;
- using System.Windows.Input;
- using SQLiteSample.Helpers;
- using SQLiteSample.Models;
- using SQLiteSample.Servcies;
- using SQLiteSample.Validator;
- using SQLiteSample.Views;
- using Xamarin.Forms;
- namespace SQLiteSample.ViewModels {
- public class AddContactViewModel : BaseContactViewModel {
- public ICommand AddContactCommand { get; private set; }
- public ICommand ViewAllContactsCommand { get; private set; }
- public AddContactViewModel(INavigation navigation){
- _navigation = navigation;
- _contactValidator = new ContactValidator();
- _contact = new ContactInfo();
- _contactRepository = new ContactRepository();
- AddContactCommand = new Command(async () => await AddContact());
- ViewAllContactsCommand = new Command(async () => await ShowContactList());
- }
- async Task AddContact() {
- var validationResults = _contactValidator.Validate(_contact);
- if (validationResults.IsValid){
- bool isUserAccept = await Application.Current.MainPage.DisplayAlert("Add Contact", "Do you want to save Contact details?", "OK", "Cancel");
- if (isUserAccept) {
- _contactRepository.InsertContact(_contact);
- await _navigation.PushAsync(new ContactList());
- }
- }
- else {
- await Application.Current.MainPage.DisplayAlert("Add Contact", validationResults.Errors[0].ErrorMessage, "Ok");
- }
- }
- async Task ShowContactList(){
- await _navigation.PushAsync(new ContactList());
- }
- public bool IsViewAll => _contactRepository.GetAllContactsData().Count > 0 ? true : false;
- }
- }
In AddContact method, we are validating ContactInfo object with help of ContactValidator before insert new contact to database.
ContactListViewModel
Above UI screen is for ContactListView. So ViewModel should have below properties and commands.
Properties: ContactList, SelectedContactItem
Commands: AddCommand, DeleteAllContactsCommand
In PCL project ViewModels folder, Add below ContactListViewModel class.
- using System.Threading.Tasks;
- using System.Windows.Input;
- using SQLiteSample.Models;
- using SQLiteSample.Servcies;
- using SQLiteSample.Views;
- using Xamarin.Forms;
- namespace SQLiteSample.ViewModels
- {
- public class ContactListViewModel : BaseContactViewModel {
- public ICommand AddCommand { get; private set; }
- public ICommand DeleteAllContactsCommand { get; private set; }
- public ContactListViewModel(INavigation navigation) {
- _navigation = navigation;
- _contactRepository = new ContactRepository();
- AddCommand = new Command(async () => await ShowAddContact());
- DeleteAllContactsCommand = new Command(async () => await DeleteAllContacts());
- FetchContacts();
- }
- void FetchContacts(){
- ContactList = _contactRepository.GetAllContactsData();
- }
- async Task ShowAddContact() {
- await _navigation.PushAsync(new AddContact());
- }
- async Task DeleteAllContacts(){
- bool isUserAccept = await Application.Current.MainPage.DisplayAlert("Contact List", "Delete All Contacts Details ?", "OK", "Cancel");
- if (isUserAccept){
- _contactRepository.DeleteAllContacts();
- await _navigation.PushAsync(new AddContact());
- }
- }
- async void ShowContactDetails(int selectedContactID){
- await _navigation.PushAsync(new DetailsPage(selectedContactID));
- }
- ContactInfo _selectedContactItem;
- public ContactInfo SelectedContactItem {
- get => _selectedContactItem;
- set {
- if (value != null){
- _selectedContactItem = value;
- NotifyPropertyChanged("SelectedContactItem");
- ShowContactDetails(value.Id);
- }
- }
- }
- }
- }
DetailsViewModel
Above UI screen is for Contact DetailsView. So ViewModel should have below properties and commands.
Properties: All properties of BaseContactViewModel as it is very similar to AddContactViewModel.
Commands: UpdateContactCommand, DeleteContactCommand
In PCL project ViewModels folder, Add below DetailsViewModel class.
- using System.Threading.Tasks;
- using System.Windows.Input;
- using SQLiteSample.Helpers;
- using SQLiteSample.Models;
- using SQLiteSample.Servcies;
- using SQLiteSample.Validator;
- using Xamarin.Forms;
- namespace SQLiteSample.ViewModels {
- public class DetailsViewModel: BaseContactViewModel {
- public ICommand UpdateContactCommand { get; private set; }
- public ICommand DeleteContactCommand { get; private set; }
- public DetailsViewModel(INavigation navigation, int selectedContactID) {
- _navigation = navigation;
- _contactValidator = new ContactValidator();
- _contact = new ContactInfo();
- _contact.Id = selectedContactID;
- _contactRepository = new ContactRepository();
- UpdateContactCommand = new Command(async () => await UpdateContact());
- DeleteContactCommand = new Command(async () => await DeleteContact());
- FetchContactDetails();
- }
- void FetchContactDetails(){
- _contact = _contactRepository.GetContactData(_contact.Id);
- }
- async Task UpdateContact() {
- var validationResults = _contactValidator.Validate(_contact);
- if (validationResults.IsValid) {
- bool isUserAccept = await Application.Current.MainPage.DisplayAlert("Contact Details", "Update Contact Details", "OK", "Cancel");
- if (isUserAccept) {
- _contactRepository.UpdateContact(_contact);
- await _navigation.PopAsync();
- }
- }
- else {
- await Application.Current.MainPage.DisplayAlert("Add Contact", validationResults.Errors[0].ErrorMessage, "Ok");
- }
- }
- async Task DeleteContact() {
- bool isUserAccept = await Application.Current.MainPage.DisplayAlert("Contact Details", "Delete Contact Details", "OK", "Cancel");
- if (isUserAccept) {
- _contactRepository.DeleteContact(_contact.Id);
- await _navigation.PopAsync();
- }
- }
- }
- }
5. How to bind Contact Views with ViewModels?
We completed the business logic in all above view models and now we can create UI in Views folder and need bind it to the view models.
Add Contact
We need to create a page that can provide UI to insert new contact details. If we observe the above UI android screens, AddContact and Contacts Details UI is almost similar. So we can build common UI with help of ContentView and then reuse it in AddContact and Details Pages.
So create Views folder in PCL and add below ContentView. Make sure UI elements should bind to relevant view model properties (Name, Mobile Number, Age, Gender, DOB, Address).
- <?xml version="1.0" encoding="UTF-8"?>
- <ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="SQLiteSample.Views.ContactView">
- <StackLayout Spacing="12">
- <Entry x:Name="txtContactName" Text="{Binding Name}" HeightRequest="40" BackgroundColor="White" Placeholder="Contact Name" HorizontalOptions="FillAndExpand"/>
- <Entry x:Name="txtMobileNumber" Keyboard="Telephone" Text="{Binding MobileNumber}" BackgroundColor="White" HeightRequest="40" Placeholder="Mobile Number" HorizontalOptions="FillAndExpand"/>
- <StackLayout Orientation="Horizontal">
- <Entry x:Name="txtAge" Text="{Binding Age}" HeightRequest="40" BackgroundColor="White" Placeholder="Age" HorizontalOptions="FillAndExpand"/>
- <Picker x:Name="GenderPicker" SelectedItem="{Binding Gender}" Title="Gender" BackgroundColor="White" HeightRequest="40" HorizontalOptions="FillAndExpand">
- <Picker.ItemsSource>
- <x:Array Type="{x:Type x:String}">
- <x:String>Male</x:String>
- <x:String>FeMale</x:String>
- </x:Array>
- </Picker.ItemsSource>
- </Picker>
- </StackLayout>
- <DatePicker x:Name="txtDOB" Date="{Binding DOB}" BackgroundColor="White" HeightRequest="40" HorizontalOptions="FillAndExpand"/>
- <Entry x:Name="txtAddress" Text="{Binding Address}" BackgroundColor="White" HeightRequest="40" Placeholder="Address" HorizontalOptions="FillAndExpand"/>
- </StackLayout>
- </ContentView>
Declare above ContentView name space in Xaml to reuse it in AddContact.
- <?xml version="1.0" encoding="UTF-8"?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:SQLiteSample.Views">
- <StackLayout Padding="20" Spacing="12">
- <local:ContactView />
- </StackLayout>
- </ContentPage>
Now in Views folder create AddContact.xaml page and add below xaml code
- <?xml version="1.0" encoding="UTF-8"?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" Title="Add Contact" BackgroundColor="#D5E7FA" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="SQLiteSample.Views.AddContact" xmlns:local="clr-namespace:SQLiteSample.Views">
- <StackLayout Padding="20" Spacing="12">
- <local:ContactView />
- <Button x:Name="SubmitButton" Command="{Binding AddContactCommand}" BorderRadius="0" Text="Save Contact" FontAttributes="Bold" TextColor="White" BackgroundColor="#5989B5"/>
- <Label Text="View All Contacts" IsVisible="{Binding IsViewAll}" x:Name="ViewLbl" TextColor="Black" HorizontalOptions="EndAndExpand" FontSize="15">
- <Label.GestureRecognizers>
- <TapGestureRecognizer Command="{Binding ViewAllContactsCommand}" NumberOfTapsRequired="1" />
- </Label.GestureRecognizers>
- </Label>
- </StackLayout>
- </ContentPage>
Set BindingContext with viewmodel in AddContact.xaml.cs like below
- using SQLiteSample.ViewModels;
- using Xamarin.Forms;
- namespace SQLiteSample.Views
- {
- public partial class AddContact : ContentPage {
- public AddContact() {
- InitializeComponent();
- BindingContext = new AddContactViewModel(Navigation);
- }
- }
- }
Contact List
We need to create a page that can display all contacts details, also to add new contact details and delete all contacts.In Views folder, create ContactList.xaml and add below code.
- <?xml version="1.0" encoding="UTF-8"?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" Title="Contact List" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="SQLiteSample.Views.ContactList">
- <Grid Padding="10,20,10,40">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto" />
- <RowDefinition Height="*" />
- <RowDefinition Height="Auto" />
- </Grid.RowDefinitions>
- <Grid Grid.Row="0">
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="*" />
- <ColumnDefinition Width="*" />
- </Grid.ColumnDefinitions>
- <Button Text="New Contact" Grid.Row="0" Grid.Column="1" FontAttributes="Bold" BorderRadius="0" HeightRequest="40" BorderColor="Black" BackgroundColor="Transparent" BorderWidth="1" TextColor="Black" Command="{Binding AddCommand}" />
- </Grid>
- <ListView x:Name="ContactListView" HasUnevenRows="true" Grid.Row="1" SeparatorColor="Black" ItemsSource="{Binding ContactList}"
- SelectedItem="{Binding SelectedContactItem, Mode=TwoWay}">
- <ListView.ItemTemplate>
- <DataTemplate>
- <ViewCell>
- <Grid Padding="10">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" />
- </Grid.RowDefinitions>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="Auto" />
- <ColumnDefinition Width="*" />
- </Grid.ColumnDefinitions>
- <Label Text="{Binding Name}" Grid.Row="0" Font="20" TextColor="Black" />
- <Label Text="{Binding MobileNumber}" Grid.Row="0" Font="20" Grid.Column="1" HorizontalOptions="EndAndExpand" HorizontalTextAlignment="End" TextColor="Black" />
- <Label Text="{Binding Address}" Grid.Row="1" Grid.Column="0" HorizontalOptions="FillAndExpand" TextColor="Black" />
- </Grid>
- </ViewCell>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
- <Button Text="Delete All Contacts" Grid.Row="2" BorderRadius="0" VerticalOptions="EndAndExpand" FontAttributes="Bold" TextColor="White" BackgroundColor="#5989B5" Command="{Binding DeleteAllContactsCommand}" />
- </Grid>
- </ContentPage>
In Above xaml code we added
- Two buttons (New Contact, Delete All Contacts)
- ListView (To display contacts list and to set ItemsSource ContactList)
Now set BindingContext with viewmodel in ContactList.xaml.cs like below
- using System;
- using SQLiteSample.Helpers;
- using SQLiteSample.Models;
- using SQLiteSample.ViewModels;
- using Xamarin.Forms;
- namespace SQLiteSample.Views {
- public partial class ContactList : ContentPage {
- public ContactList() {
- InitializeComponent();
- }
- protected override void OnAppearing() {
- this.BindingContext = new ContactListViewModel(Navigation);
- }
- }
- }
DetailsPage:
We need to create a page that can display particular contact details, also to update/delete contact details.
In Views folder, create DetailsPage.xaml and add below code.
- <?xml version="1.0" encoding="UTF-8"?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" Title="Contact Details" BackgroundColor="#D5E7FA"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:SQLiteSample.Views" x:Class="SQLiteSample.Views.DetailsPage">
- <StackLayout Padding="20" Spacing="12">
- <local:ContactView />
- <Button Text="Update" BorderRadius="0" Margin="0,30,0,0" FontAttributes="Bold" TextColor="White" BackgroundColor="#5989B5" Command="{Binding UpdateContactCommand}" />
- <Button Text="Delete" BorderRadius="0" Margin="0,30,0,0" FontAttributes="Bold" TextColor="White" BackgroundColor="#5989B5" Command="{Binding DeleteContactCommand}" />
- </StackLayout>
- </ContentPage>
Now set BindingContext with viewmodel in DetailsPage.xaml.cs like below
- using SQLiteSample.ViewModels;
- using Xamarin.Forms;
- namespace SQLiteSample.Views {
- public partial class DetailsPage : ContentPage {
- public DetailsPage(int contactID) {
- InitializeComponent();
- this.BindingContext = new DetailsViewModel(Navigation, contactID);
- }
- }
- }
Demo screens from iOS:
You can directly work on below sample source code to understand the this article.
You can also see to run this article source code from below youtube video. Also for more videos please don't forget to SUBSCRIBE our youtube channel from here.
FeedBack Note: Please share your thoughts, what you think about this post, Is this post really helpful for you? I always welcome if you drop comments on this post and it would be impressive.
This article is excellent. Thank you.
ReplyDeleteHi Author just now i found your blog its really awesome. Keep this work. It will more helpful for xamarin app developers. Hire Xamarin Developer
ReplyDeleteError CS0246 The type or namespace name 'SQLite' could not be found (are you missing a using directive or an assembly reference?) SQLiteSample C:\Users\1011696\source\repos\SQLiteSample\SQLiteSample\SQLiteSample\Helpers\ISQLite .cs
ReplyDeleteHelp to resolve the issue. Tried in many ways. Could not sort
Really Awesome
ReplyDeletethank you!
ReplyDeleteJust started on Xamarin I already managed to work with SQLite internally but this is a huge kick-starter for me on MVVM. Thank you.
ReplyDeleteUnhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. occurred - getting this error
ReplyDeleteNice article !
ReplyDeleteone question, in case we have a few models, what kind of changes should be done in Database Helper ? Or there should be created helper file for each model ?
ReplyDeleteCan you send the link from the source code? above doesn't work
Why was this link directed to https://docs.microsoft.com/en-us/samples/browse/?redirectedfrom=MSDN-samples. Where can I get the source code.. Great Article I am getting an exception null pointer database is not being connected sqliteconnection = DependencyService.Get().GetConnection();
ReplyDeleteSystem.NullReferenceException: 'Object reference not set to an instance of an object.'
Source code would help
Thanks
Why is the code link directed to https://docs.microsoft.com/en-us/samples/browse/?redirectedfrom=MSDN-samples. Where can I get the a link to the source its great example and I have learned a lot just compiling it on my own.
ReplyDeleteBut
I am getting a System.NullReferenceException: 'Object reference not set to an instance of an object.' from this line
sqliteconnection = DependencyService.Get().GetConnection(); GetConnection is not connecting to the database and passing the pointer back
Thanks
Great article - where is the source code please?
ReplyDeleteThanks
Hello Guys
ReplyDeleteSorry say that, Microsoft broken all MSDN code sample gallery links. So I have to start prepare this article source code again and need to push them to Github. Will share the download link as soon as possible.
hi can you please give me the source code link..i really need it..thanks
ReplyDeleteGreat article!!! But where is the source code please?
ReplyDeleteThanks
I found the source code here: https://github.com/microsoftarchive/msdn-code-gallery-community-s-z/tree/master/SQLite%20sample%20for%20beginners%20in%20Xamarin.Forms%20(C%23%20-%20Xaml)
ReplyDeleteIn order to download, you need to download the whole archive and extract out only what you want: https://github.com/microsoftarchive/msdn-code-gallery-community-s-z
Thanks for the article.
Hi Guys,
ReplyDeleteI updated the download link, please click "Download Code" from bottom of the article.
Thanks
Subramanyam Raju