Student Info In Xamarin.Forms Application Using SQLite For Android And UWP

Student Information is used for day-to-day activities in the educational environment. Reading this article, you can learn how to perform local database operation in Xamarin Forms application using SQLite for Android and Universal Windows Platform with XAML and Visual C# in cross-platform application development.

SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The code for SQLite is in the public domain and is thus free for use for any purpose, commercial or private.
 
The following important tools are required for developing UWP,
  1. Windows 10 (Recommended)
  2. Visual Studio 2017 Community (https://www.visualstudio.com/downloads/ )

Now, we can discuss step by step App development.

Step 1

Open Visual studio 2017 -> Start -> New Project-> Select Cross-Platform (under Visual C#->Cross Platform App-> MobileApp (Xamarin.Forms) -> Give the Suitable Name for your App (XamSqlitestud) ->OK.

 

Step 2

Select the Cross-Platform template as a Blank APP ->Set Platform as Android and UWP and code sharing strategy as .NET standard, Afterwards, Visual Studio creates 3 projects (Portable, Droid, UWP) and displays Getting Started.XamarinPage.

 

Step 3

Add the SQLite Reference, Right Click the Solution(XamWeather)-> Select Manage NuGet Packages for Solution.

Browse and Install the Reference,

 

Step 4

Add the Student Class for data binding,

 

Add the following Namespace and code in Student.cs,

  1. using SQLite;  
  2. public class Student {  
  3.     [PrimaryKey, AutoIncrement]  
  4.     public int stdid {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     [NotNull]  
  9.     public string stdname {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public string stdcourse {  
  14.         get;  
  15.         set;  
  16.     }  
  17.     public int stdage {  
  18.         get;  
  19.         set;  
  20.     }  
  21. }  

Step 5

Add the StudDB Class for SQLite operations,

 

Add the following Namespace and code in StudDB.cs,

  1. using System.Threading.Tasks;  
  2. using SQLite;  
  3. public class StudDB {  
  4.     readonly SQLiteAsyncConnection database;  
  5.     public StudDB(string dbpath) {  
  6.         database = new SQLiteAsyncConnection(dbpath);  
  7.         database.CreateTableAsync < Student > ().Wait();  
  8.     }  
  9.     public Task < List < Student >> GetStudentsAsync() {  
  10.         return database.Table < Student > ().ToListAsync();  
  11.     }  
  12.     public Task < Student > GetStudentAsync(int id) {  
  13.         return database.Table < Student > ().Where(i => i.stdid == id).FirstOrDefaultAsync();  
  14.     }  
  15.     public Task < int > SaveStudentAsync(Student student) {  
  16.         if (student.stdid != 0) {  
  17.             return database.UpdateAsync(student);  
  18.         } else {  
  19.             return database.InsertAsync(student);  
  20.         }  
  21.     }  
  22.     public Task < int > DeleteStudentAsync(Student student) {  
  23.         return database.DeleteAsync(student);  
  24.     }  
  25.     public Task < int > EditStudent(Student student) {  
  26.         return database.UpdateAsync(student);  
  27.     }  
  28. }  

 

Step 6

Add the IStdLocHelper interface for SQLite operations between projects,

 

Add the following Namespace and code in IStdLocHelper.cs,

  1. public interface IStdLocHelper {  
  2.     string GetLocalFilePath(string filename);  
  3. }  

Step 7

Add the LocalFileHelper class in XamSqlitestud.UWP for implementing IStdLocHelper interface to perform SQLite operations in UWP project,

 

Add the following Namespace and code in LocalFileHelper.cs,

  1. using Windows.Storage;  
  2. using XamSqlitestud.UWP;  
  3. using System.IO;  
  4. using Xamarin.Forms;  
  5. [assembly: Dependency(typeof(LocalFileHelper))]  
  6. namespace XamSqlitestud.UWP {  
  7.     public class LocalFileHelper: IStdLocHelper {  
  8.         public string GetLocalFilePath(string filename) {  
  9.             string docFolder = ApplicationData.Current.LocalFolder.Path;  
  10.             string libFolder = Path.Combine(docFolder, "Databases");  
  11.             if (!Directory.Exists(libFolder)) {  
  12.                 Directory.CreateDirectory(libFolder);  
  13.             }  
  14.             return Path.Combine(libFolder, filename);  
  15.         }  
  16.     }  
  17. }  

Step 8

Add the LocalFileHelper class in XamSqlitestud.Droid for implementing IStdLocHelper interface to perform SQLite operations in UWP project,

 

Add the following Namespace and code in LocalFileHelper.cs,

  1. using System.IO;  
  2. using Xamarin.Forms;  
  3. using XamSqlitestud.Droid;  
  4. [assembly: Dependency(typeof(LocalFileHelper))]  
  5. namespace XamSqlitestud.Droid {  
  6.     public class LocalFileHelper: IStdLocHelper {  
  7.         public string GetLocalFilePath(string filename) {  
  8.             string docFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);  
  9.             string libFolder = Path.Combine(docFolder, "..""Library""Databases");  
  10.             if (!Directory.Exists(libFolder)) {  
  11.                 Directory.CreateDirectory(libFolder);  
  12.             }  
  13.             return Path.Combine(libFolder, filename);  
  14.         }  
  15.     }  
  16. }  

Step 9

Add the following code in App.xaml.cs for dependency service,

  1. static StudDB database;  
  2. public static StudDB Database {  
  3.     get {  
  4.         if (database == null) {  
  5.             database = new StudDB(DependencyService.Get < IStdLocHelper > ().GetLocalFilePath("Student1.db3"));  
  6.         }  
  7.         return database;  
  8.     }  
  9. }  

Step 10

For User View, in MainPage.Xaml Page , add the Listview with data template for student list,

  1. <ContentPage.Content>  
  2.     <ListView x:Name="StudListview" ItemSelected="Student_Itemselected">  
  3.         <ListView.ItemTemplate>  
  4.             <DataTemplate>  
  5.                 <TextCell Text="{Binding stdname}" Detail="{Binding stdcourse}" /> </DataTemplate>  
  6.         </ListView.ItemTemplate>  
  7.     </ListView>  
  8. </ContentPage.Content>  

Step 11

Add new Contentpage- AddingStudent for adding new student,

 

Add the following controls code for new student,

  1. <ContentPage.Content>  
  2.     <StackLayout Padding="10" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">  
  3.         <Grid>  
  4.             <Label Text="Name" Grid.Row="0" Grid.Column="0" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  5.             <Entry Text="{Binding stdname}" Grid.Row="0" Grid.Column="1" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  6.             <Label Text="Course" Grid.Row="1" Grid.Column="0" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  7.             <Entry Text="{Binding stdcourse}" Grid.Row="1" Grid.Column="1" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  8.             <Label Text="Age" Grid.Row="2" Grid.Column="0" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  9.             <Entry Text="{Binding stdage}" Grid.Row="2" Grid.Column="1" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" /> </Grid>  
  10.         <Button Text="Save" HorizontalOptions="FillAndExpand" BackgroundColor="Blue" TextColor="White" Clicked="Save_Clicked" />  
  11.         <Button Text="Cancel" HorizontalOptions="FillAndExpand" BackgroundColor="Blue" TextColor="White" Clicked="Cancel_Clicked" /> </StackLayout>  
  12. </ContentPage.Content>  

Step 12

Add new Contentpage - EditingStudent for Editing (update or delete)a student,

 

Add the following controls code for Editing (update or delete)a student ,

  1. <StackLayout Padding="10" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">  
  2.     <Grid>  
  3.         <Label Text="Name" Grid.Row="0" Grid.Column="0" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  4.         <Entry Text="{Binding stdname}" Grid.Row="0" Grid.Column="1" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  5.         <Label Text="Course" Grid.Row="1" Grid.Column="0" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  6.         <Entry Text="{Binding stdcourse}" Grid.Row="1" Grid.Column="1" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  7.         <Label Text="Age" Grid.Row="2" Grid.Column="0" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  8.         <Entry Text="{Binding stdage}" Grid.Row="2" Grid.Column="1" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" /> </Grid>  
  9.     <Button Text="Save" HorizontalOptions="FillAndExpand" BackgroundColor="Blue" TextColor="White" Clicked="Save_Clicked" />  
  10.     <Button Text="Delete" HorizontalOptions="FillAndExpand" BackgroundColor="Blue" TextColor="White" Clicked="OnDeleteClicked" />   
  11. </StackLayout>  

Step 13

Add the following code in MainPage.Xaml.cs for adding new student using Toolbar Item + Click,

  1. public MainPage() {  
  2.     InitializeComponent();  
  3.     this.Title = "Student List";  
  4.     var toolbarItem = new ToolbarItem {  
  5.         Text = "+"  
  6.     };  
  7.     toolbarItem.Clicked += async (sender, e) => {  
  8.         await Navigation.PushAsync(new AddStudent() {  
  9.             BindingContext = new Student()  
  10.         });  
  11.     };  
  12.     ToolbarItems.Add(toolbarItem);  
  13. }  
  14. protected async override void OnAppearing() {  
  15.     base.OnAppearing();  
  16.     StudListview.ItemsSource = await App.Database.GetStudentsAsync();  
  17. }  
  18. async void Student_Itemselected(object sender, SelectedItemChangedEventArgs e) {  
  19.     if (e.SelectedItem != null) {  
  20.         await Navigation.PushAsync(new EditStudent() {  
  21.             BindingContext = e.SelectedItem as Student  
  22.         });  
  23.     }  
  24. }  
  25. }  

Step 14

Add the following code in Addstudent.Xaml.cs for Save and Cancel Buttons,

  1. async void Save_Clicked(object sender, System.EventArgs e) {  
  2.     var personItem = (Student) BindingContext;  
  3.     await App.Database.SaveStudentAsync(personItem);  
  4.     await Navigation.PopAsync();  
  5. }  
  6. async void Cancel_Clicked(object sender, System.EventArgs e) {  
  7.     await Navigation.PopAsync();  
  8. }  

Step 15

Add the following code in EditStudent.Xaml.cs for Save and Delete Buttons,

  1. async void Save_Clicked(object sender, System.EventArgs e) {  
  2.     var personItem = (Student) BindingContext;  
  3.     await App.Database.SaveStudentAsync(personItem);  
  4.     await Navigation.PopAsync();  
  5. }  
  6. public async void OnDeleteClicked(object sender, System.EventArgs e) {  
  7.     bool accepted = await DisplayAlert("Confirm""Are you Sure ?""Yes""No");  
  8.     if (accepted) {  
  9.         var personItem = (Student) BindingContext;  
  10.         await App.Database.DeleteStudentAsync(personItem);  
  11.         await Navigation.PopAsync();  
  12.     }  
  13.     await Navigation.PushAsync(new AddStudent());  
  14. }  
  15. }  

Step 16

Deploy your App to Android Emulator and Local Machine (UWP) and the output of the XamSqlitestud App is,

 
 

After Press the + Toolbar button for Adding a new student in UWP and Android,

 
 

After adding new student detail in UWP and Android,

 
 

Select specific student for Edit in UWP and Android,

 
 

Editing the student Course in UWP and Android,

 
 
After Editing a student Course in UWP and Android,

 

To perform delete a student in UWP and Android,
 
 

After Deleting a student in UWP and Android,

 
 

Summary

Now, you have successfully tested student info using SQLite in Xamarin Forms application for Cross-Platform Application Development using Visual C# and Xamarin.