Thursday, August 18, 2016

An Introduction to Xamarin.Forms and SQLite_part 2(end)


Step 5: Add the Android Implementation

This step is very similar to the previous one. The only difference is that the code will change a little due to the fact that the location of the database file will be different. You will still need to add the appropriate packages to the Android project (SQLite.Net PCL and SQLite.NET PCL - XamarinAndroid) as you did before. Once you have completed that, you can add the appropriate code in a new class named SQLite_Android.
  1. using System;
  2. using System.IO;
  3. using Xamarin.Forms;
  4. using IntroToSQLite.Android;
  5.  
  6. [assembly: Dependency(typeof(SQLite_Android))]
  7.  
  8. namespace IntroToSQLite.Android
  9. {
  10.     public class SQLite_Android: ISQLite
  11.     {
  12.         public SQLite_Android ()
  13.         {
  14.         }
  15.  
  16.         #region ISQLite implementation
  17.  
  18.         public SQLite.Net.SQLiteConnection GetConnection ()
  19.         {
  20.             var fileName = "RandomThought.db3";
  21.             var documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
  22.             var path = Path.Combine (documentsPath, fileName);
  23.  
  24.             var platform = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid ();
  25.             var connection = new SQLite.Net.SQLiteConnection (platform, path);
  26.  
  27.             return connection;
  28.         }
  29.  
  30.         #endregion
  31.     }
  32. }
You now have a working implementation of the ISQLite interface from the perspective of your Android app.

Step 6: Add the Windows Phone Implementation

Since I am running this app from a Mac, I won't be creating the Windows Phone implementation, but if you would like to do this, you can.

The first step is to add support to your Windows Phone project for SQLite. As mentioned earlier, SQLite comes by default on iOS and Android. This is not true for Windows Phone, but it is supported. To get it installed, you can follow the instructions found on the Xamarin website.

After installing SQLite, the process of adding the functionality for Windows Phone will be almost exactly the same, except that the packages to install are SQLite.Net PCL and SQLite.Net PCL - WindowsPhone 8 Platform. With these packages installed, you can create the Windows Phone implementation of the ISQLite interface.
  1. using System;
  2. using System.IO;
  3. using Xamarin.Forms;
  4. using IntroToSQLite.WinPhone;
  5.  
  6. [assembly: Dependency(typeof(SQLite_WinPhone)]
  7.  
  8. namespace IntroToSQLite.WinPhone
  9. {
  10.     public class SQLite_WinPhone: ISQLite
  11.     {
  12.         public SQLite_WinPhone ()
  13.         {
  14.         }
  15.  
  16.         #region ISQLite implementation
  17.  
  18.         public SQLite.Net.SQLiteConnection GetConnection ()
  19.         {
  20.             var fileName = "RandomThought.db3";
  21.             var path = Path.Combine (ApplicationData.Current.LocalFolder.Path, fileName);
  22.  
  23.             var platform = new SQLite.Net.Platform.WindowsPhone8.SQLitePlatformWP8 ();
  24.             var connection = new SQLite.Net.SQLiteConnection (platform, path);
  25.  
  26.             return connection;
  27.         }
  28.  
  29.         #endregion
  30.     }
  31. }
There you have it. Now you have all of your native implementations complete. It's time to give this app a user interface and get your data into the database.

Step 7: Adding the User Interface

Since this tutorial is well into the topic of Xamarin.Forms, I'm going to assume that you at least have a basic working knowledge of Xamarin.Forms. With this assumption in mind, I'm not going to go into a lot of detail on the process of creating the user interface. If you need more background information on Xamarin.Forms, check out my other Xamarin.Forms tutorials on Tuts+.

The user interface is going to consist of two separate pages. The first page will contain a list of all the thoughts we have entered in a list while the second page will let the user enter a new thought. Let's build these pages.

Create the ListView

We will first focus on creating the first page that will contain a list of RandomThought objects. Start by creating a new file in the PCL (or Shared) project and name it RandomThoughtsPage. Replace the default implementation with the following:
  1. using System;
  2. using Xamarin.Forms;
  3.  
  4. namespace IntroToSQLite
  5. {
  6.     public class RandomThoughtsPage: ContentPage {
  7.         private RandomThoughtDatabase _database;
  8.         private ListView _thoughtList;
  9.  
  10.         public RandomThoughtsPage (RandomThoughtDatabase database)
  11.         {
  12.             _database = database;
  13.             Title = "Random Thoughts";
  14.             var thoughts = _database.GetThoughts ();
  15.  
  16.             _thoughtList = new ListView ();
  17.             _thoughtList.ItemsSource = thoughts;
  18.             _thoughtList.ItemTemplate = new DataTemplate (typeof(TextCell));
  19.             _thoughtList.ItemTemplate.SetBinding (TextCell.TextProperty, "Thought");
  20.             _thoughtList.ItemTemplate.SetBinding (TextCell.DetailProperty, "CreatedOn");
  21.  
  22.             var toolbarItem = new ToolbarItem {
  23.                 Name = "Add",
  24.                 Command = new Command(() => Navigation.PushAsync(new ThoughtEntryPage(this, database)))
  25.             };
  26.  
  27.             ToolbarItems.Add (toolbarItem);
  28.  
  29.             Content = _thoughtList;
  30.         }
  31.  
  32.         public void Refresh() {
  33.             _thoughtList.ItemsSource = _database.GetThoughts ();
  34.         }
  35.     }
  36. }
Most of the work done in this class is in the constructor. The constructor allows us to pass in an instance of the RandomThoughtsDatabase to get all the saved thoughts. We set the Title property of the page to "Random Thoughts", retrieve all the existing thoughts, create a new instance of a ListView, and create a ToolbarItem that will allow us to click a button to bring up the entry page. We haven't implemented that yet, but we will shortly.

To get our new RandomThoughtsPage up on the screen, we need to make a little modification to the App.cs file. Within this file, modify the GetMainPage method to look like the following:
  1. public static Page GetMainPage ()
  2.     var database = new RandomThoughtDatabase ();
  3.  
  4.     return new NavigationPage (new RandomThoughtsPage (database));
  5. }
The GetMainPage method now creates a new instance of our RandomThoughtDatabase class and returns a new instance of the RandomThoughtsPage. With this change, our iOS and Android apps should look something like this:


Create the Entry Page

We now have a list page for all of our RandomThought objects, but we don't have a way to enter new ones. For that, we will create another page similar to the previous page. Create a new file in your PCL (or Shared) project and call it ThoughtEntryPage. Replace the default implementation with the following:
  1. using System;
  2. using Xamarin.Forms;
  3.  
  4. namespace IntroToSQLite
  5. {
  6.     public class ThoughtEntryPage: ContentPage {
  7.         private RandomThoughtsPage _parent;
  8.         private RandomThoughtDatabase _database;
  9.  
  10.         public ThoughtEntryPage ( RandomThoughtsPage parent, RandomThoughtDatabase database)
  11.         {
  12.             _parent = parent;
  13.             _database = database;
  14.             Title = "Enter a Thought";
  15.  
  16.             var entry = new Entry ();
  17.             var button = new Button {
  18.                 Text = "Add"
  19.             };
  20.  
  21.             button.Clicked += async (object sender, EventArgs e) => {
  22.                 var thought = entry.Text;
  23.  
  24.                 _database.AddThought(thought);
  25.  
  26.                 await Navigation.PopAsync();
  27.  
  28.  
  29.                 _parent.Refresh();
  30.             };
  31.  
  32.             Content = new StackLayout {
  33.                 Spacing = 20,
  34.                 Padding = new Thickness(20),
  35.                 Children = { entry, button },
  36.             };
  37.         }
  38.     }
  39. }
In this class, all the work is done within the constructor. We get a reference to the parent page, RandomThoughtsPage, as well as the database. The rest is basic setup code with an Entry object for entering text and a Button.

Once the user taps the Button, we use the database to add the new thought, dismiss the page, go back to the list page, and call the Refresh method to update the ListView. Once this is all wired up, we can run it to actually enter some values.

Entering Thoughts

Here is what it looks like on iOS and Android to enter some of your thoughts:



Viewing the List

After you have entered a few thoughts, your list will look something like this:



Conclusion

There you have it. You now have the ability to add database functionality to your Xamarin.Forms app to store and retrieve any sort of data with ease.

To continue your learning journey with Xamarin.Forms and SQLite, I give you the following challenge. See if you can enhance this application to enable deleting thoughts and update the list page in a similar fashion as the entry page. Good luck and happy coding.
Written by Derek Jensen

If you found this post interesting, follow and support us.
Suggest for you:

The Complete Android & Java Course - Build 21 Android Apps

Android Application Programming - Build 20+ Android Apps

iOS 10 Message Extension App Reskinning without Coding

iOS 10 Projects: Build Amazing Apps with Apple's Newest iOS

iOS 10 & Swift 3: From Beginner to Paid Professional

No comments:

Post a Comment