Introduction:
If you want to implement sqlite database application for windowsphone 8.0,you may helped from my previous article.Now from this article we will learn about 'Sqlite support in WindowsPhone Store 8.1'.This article is compared with my previous article,so that we can easily understand the changes in WP8.0 & WP8.1 to setup Sqlite environment.
Requirements:
- This sample is targeted for windowsphone store 8.1 OS,So make sure you’ve downloaded and installed the Windows Phone 8.1 SDK. For more information, see Get the SDK.
- I assumes that you’re going to test your app on the Windows Phone emulator. If you want to test your app on a phone, you have to take some additional steps. For more info, see Register your Windows Phone device for development.
- This post assumes you’re using Microsoft Visual Studio Express 2013 for Windows.
- This sample is targeted for windowsphone store 8.1 OS,So make sure you’ve downloaded and installed the Windows Phone 8.1 SDK. For more information, see Get the SDK.
- I assumes that you’re going to test your app on the Windows Phone emulator. If you want to test your app on a phone, you have to take some additional steps. For more info, see Register your Windows Phone device for development.
- This post assumes you’re using Microsoft Visual Studio Express 2013 for Windows.
Table of Contents:
Some extensions to be installed in order to interact with Sqlite from your WP8.1 app.And now it is very easy to setup sqlite environment in our apps.So this post covers all about sqlite with beginners level like this.
1)How can i setup SQLite environment?
2)How to perform all SQLite CRUD operations ?
3)How to bind SQLite data to listbox?
4)How to explore my"SQLite" database data?
Description:
SQLite is a very light weight database. In this tutorial I’ll be discussing how to write classes to handle all SQLite operations.So let's start with above hierarchy which is earlier discussed in "Table of Contents".
1)How can i setup SQLite environment?
Sqlite is directly not available in windowsphone ,and don't worry now it is very easy to setup sqlite in windowsphone apps.So we need to follow two steps only (i.e Installing SQLite for Windows Phone SDK,Installing sqlite-net-wp8 package)
1.1)Installing SQLite for Windows Phone SDK:
It’s worth noting that the current version (3.8.8.0) has a flaw in the package metadata that prevent it to show up in the Visual Studio 2013 "Tools | Extensions and Updates" page. You need to go to the web page, download and install the VSIX package by yourself:
Open Microsoft Visual Studio Express 2013 for Windows and then create new project type Blank App(Ex:SQLiteWp8.1)
Open Solution explorer,Right click on 'References' folder of your current project.
Then add the reference to the "SQLite for WindowsPhone 8.1" library:
When done, you can see that the proper references to SQLite and Visual C++ 2013 Runtime have been added to respective project:
You may have already noticed, that the references show a warning symbols,to resolve that the next thing to do, before compiling the solution is changing the architecture of the target platform. This is the fact that the engine of Sqlite is written in C ++, and the default target platform set in the project is Any CPU. This mode is not supported. To do this in the main menu of VisualStudio have the command "Compile", then "Configuration Manager", as shown in the figure.
In the next dialog, we note that we have several choices of platforms, Any CPU (the default), ARM, x64 and x86.
We have to select the target platform second, where we are trying the application. If we use a tablet, or a phone with ARM processor, we have to select the ARM platform. If we are using the emulator or in the case of Windows Phone, a PC in the case of Windows, we have to select x86 or x64, everything depends on your processor if 32 or 64 bits. In my case, I tried the sample application on a emulator with Windows Phone OS 8.1, so I chose the way of configuration x86.
1.2)Installing sqlite-net package:
After installing the library for SQLite, we need sqlite-net NuGet package.With this library, we will be able to perform all the operations that you normally do in a database, such as Insert, Delete, Update and run search queries. Sqlite-net also offers an approach typical ORM. This package provides two helper classes (SQLite.cs and SQLiteAsync.cs),So to install it right click on your project (i.e in my case project name is SQLiteWp8.1) =>Click on "Manage NuGet Packages" and search for "sqlite-net" => Click on "Install" button.After that we should found below dialog:
***Wow now whole SQLite set up process is completed,so now we are going to work with all CRUD operations***
2)How to perform all SQLite CRUD operations ?
Note: From this step on-wards,most of content will be same as my previous article.Please be note a few changes made in this post.
So its time to perform all SQLite CRUD(Create,Read,Update,Delete) operations.So my thought is in this sample i made one single "DatabaseHelperClass.cs" class for whole application and handling the SQLite operations with this helper class. Lets see first my table structure first
So its time to perform all SQLite CRUD(Create,Read,Update,Delete) operations.So my thought is in this sample i made one single "DatabaseHelperClass.cs" class for whole application and handling the SQLite operations with this helper class. Lets see first my table structure first
Here i am trying to create Table name is "Contacts" in "ContactsManager.sqlite" database.So my class "Contacts" with all getter and setter methods(Id,Name,PhoneNumber,CreatedDate) to maintain single contact as an object.
C#
public class Contacts { //The Id property is marked as the Primary Key [SQLite.PrimaryKey, SQLite.AutoIncrement] public int Id { get; set; } public string Name { get; set; } public string PhoneNumber { get; set; } public string CreationDate { get; set; } public Contacts() { //empty constructor } public Contacts(string name, string phone_no) { Name = name; PhoneNumber = phone_no; CreationDate = DateTime.Now.ToString(); } }
2.1)Writing DatabaseHelper Class to handle database operations(i.e CRUD):
C#
//This class for perform all database CRUD operations public class DatabaseHelperClass { SQLiteConnection dbConn; //Create Tabble public async Task<bool> onCreate(string DB_PATH) { try { if (!CheckFileExists(DB_PATH).Result) { using (dbConn = new SQLiteConnection(DB_PATH)) { dbConn.CreateTable<Contacts>(); } } return true; } catch { return false; } } private async Task<bool> CheckFileExists(string fileName) { try { var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName); return true; } catch { return false; } } // Retrieve the specific contact from the database. public Contacts ReadContact(int contactid) { using (var dbConn = new SQLiteConnection(App.DB_PATH)) { var existingconact = dbConn.Query<Contacts>("select * from Contacts where Id =" + contactid).FirstOrDefault(); return existingconact; } } // Retrieve the all contact list from the database. public ObservableCollection<Contacts> ReadContacts() { using (var dbConn = new SQLiteConnection(App.DB_PATH)) { List<Contacts> myCollection = dbConn.Table<Contacts>().ToList<Contacts>(); ObservableCollection<Contacts> ContactsList = new ObservableCollection<Contacts>(myCollection); return ContactsList; } } //Update existing conatct public void UpdateContact(Contacts contact) { using (var dbConn = new SQLiteConnection(App.DB_PATH)) { var existingconact = dbConn.Query<Contacts>("select * from Contacts where Id =" + contact.Id).FirstOrDefault(); if (existingconact != null) { existingconact.Name = contact.Name; existingconact.PhoneNumber = contact.PhoneNumber; existingconact.CreationDate = contact.CreationDate; dbConn.RunInTransaction(() => { dbConn.Update(existingconact); }); } } } // Insert the new contact in the Contacts table. public void Insert(Contacts newcontact) { using (var dbConn = new SQLiteConnection(App.DB_PATH)) { dbConn.RunInTransaction(() => { dbConn.Insert(newcontact); }); } } //Delete specific contact public void DeleteContact(int Id) { using (var dbConn = new SQLiteConnection(App.DB_PATH)) { var existingconact = dbConn.Query<Contacts>("select * from Contacts where Id =" + Id).FirstOrDefault(); if (existingconact != null) { dbConn.RunInTransaction(() => { dbConn.Delete(existingconact); }); } } } //Delete all contactlist or delete Contacts table public void DeleteAllContact() { using (var dbConn = new SQLiteConnection(App.DB_PATH)) { //dbConn.RunInTransaction(() => // { dbConn.DropTable<Contacts>(); dbConn.CreateTable<Contacts>(); dbConn.Dispose(); dbConn.Close(); //}); } } }
3)How to bind SQLite data to listbox?
In above step 2.1 i created one Database helper class name is "DatabaseHelperClass.cs" which is main head for this sample to perform all SQlite operations.Lets first see my project hierarchy like this
In the app.xaml class lets create a database. In the constructor we check if the database exists and if it does not we create it. Since if there is no file exists ,it will get an exception.
C#
public partial class App : Application { public static string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "ContactsManager.sqlite"));//DataBase Name public App() { if (!CheckFileExists("ContactsManager.sqlite").Result) { using (var db = new SQLiteConnection(DB_PATH)) { db.CreateTable<Contacts>(); } } } private async Task<bool> CheckFileExists(string fileName) { try { var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName); return true; } catch { } return false; }
Next I divided my project into MVVM pattern for simplicity.So in Model folder i placed table class name is "Contacts.cs".In ViewModels i placed DB helpers classes(DatabaseHelperClass.cs & ReadAllContactsList.cs).And finally Views folder i placed All my three UI related pages
- AddConatct.xaml:This page for adding contact to database,when click on "Add Contact" button it will be add contact in database like this
C#
private async void AddContact_Click(object sender, RoutedEventArgs e) { DatabaseHelperClass Db_Helper = new DatabaseHelperClass();//Creating object for DatabaseHelperClass.cs from ViewModel/DatabaseHelperClass.cs if (NametxtBx.Text != "" & PhonetxtBx.Text != "") { Db_Helper.Insert(new Contacts(NametxtBx.Text, PhonetxtBx.Text)); Frame.Navigate(typeof(ReadContactList));//after add contact redirect to contact listbox page } else { MessageDialog messageDialog = new MessageDialog("Please fill two fields");//Text should not be empty await messageDialog.ShowAsync(); } }
- ReadContactList.xaml:This page for displaying all DB contact list with listbox.And in this screen there is two buttons(Add Contact & DeleteAll) for correspondingly add contact to DB / Delete entire table data.Firstly i made following listbox datatemplate for binding database contacts
XAML
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel Width="400" Orientation="Horizontal" Grid.Row="0"> <Button Margin="20,0,0,0" Content="Add Contact" Click="AddContact_Click"/> <Button Name="Btn_Delete" Margin="100,0,0,0" Content="DeleteAll" Click="DeleteAll_Click"/> </StackPanel> <ListBox Background="Transparent" Margin="6" Height="auto" BorderThickness="2" MaxHeight="580" Grid.Row="1" x:Name="listBoxobj" SelectionChanged="listBoxobj_SelectionChanged"> <ListBox.ItemTemplate> <DataTemplate> <Grid Width="350" > <Border Margin="5" BorderBrush="White" BorderThickness="1"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <TextBlock Margin="5,0,0,0" Grid.Row="0" x:Name="NameTxt" TextWrapping="Wrap" Text="{Binding Name}" FontSize="28" Foreground="White"/> <TextBlock Grid.Row="0" Text=">" FontSize="28" HorizontalAlignment="Right" VerticalAlignment="Center" Foreground="White"/> <TextBlock Margin="5,0,0,0" Grid.Row="1" x:Name="PhoneTxt" TextWrapping="Wrap" Foreground="White" FontSize="18" Text="{Binding PhoneNumber}" /> <TextBlock HorizontalAlignment="Right" Margin="0,0,35,0" Grid.Row="3" x:Name="CreateddateTxt" Foreground="White" FontSize="18" TextWrapping="Wrap" Text="{Binding CreationDate}" /> </Grid> </Border> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid>
C#
private void ReadContactList_Loaded(object sender, RoutedEventArgs e) { ReadAllContactsList dbcontacts = new ReadAllContactsList(); DB_ContactList = dbcontacts.GetAllContacts();//Get all DB contacts if (DB_ContactList.Count > 0) { Btn_Delete.IsEnabled = true; } listBoxobj.ItemsSource = DB_ContactList.OrderByDescending(i => i.Id).ToList();//Binding DB data to LISTBOX and Latest contact ID can Display first. }
When "Add Contact" button is clicked is navigated to "AddConatct.xaml" page to add contact in DB.
When "DeleteAll" button is clicked ,i done like this
C#
private void AddContact_Click(object sender, RoutedEventArgs e) { Frame.Navigate(typeof(AddConatct)); }
C#
private async void DeleteAll_Click(object sender, RoutedEventArgs e) { var dialog = new MessageDialog("Are you sure you want to remove all your data ?"); dialog.Commands.Add(new UICommand("No", new UICommandInvokedHandler(Command))); dialog.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(Command))); await dialog.ShowAsync(); }private void Command(IUICommand command) { if (command.Label.Equals("Yes")) { DatabaseHelperClass Db_Helper = new DatabaseHelperClass(); Db_Helper.DeleteAllContact();//delete all DB contacts DB_ContactList.Clear();//Clear collections Btn_Delete.IsEnabled = false; listBoxobj.ItemsSource = DB_ContactList; } }
C#
private void listBoxobj_SelectionChanged(object sender, SelectionChangedEventArgs e) { int SelectedContactID = 0; if (listBoxobj.SelectedIndex != -1) { Contacts listitem = listBoxobj.SelectedItem as Contacts;//Get slected listbox item contact ID Frame.Navigate(typeof(Delete_UpdateContacts),SelectedContactID=listitem.Id); } }
- Delete_UpdateContacts.xaml:This page is for updating/delete selected contact details
See in above when listbox item is selected ,i passed selected contact Id as query string,so in this i get that id in "OnNavigatedTo" method like this
C#
protected override void OnNavigatedTo(NavigationEventArgs e) { Selected_ContactId = int.Parse(e.Parameter.ToString()); currentcontact = Db_Helper.ReadContact(Selected_ContactId);//Read selected DB contact NametxtBx.Text = currentcontact.Name;//get contact Name PhonetxtBx.Text = currentcontact.PhoneNumber;//get contact PhoneNumber }
When "Delete" button is pressed i done like this.
When "Update" button is pressed i done like this.
C#
private void DeleteContact_Click(object sender, RoutedEventArgs e) { Db_Helper.DeleteContact(Selected_ContactId);//Delete selected DB contact Id. Frame.Navigate(typeof(ReadContactList)); }
C#
private void UpdateContact_Click(object sender, RoutedEventArgs e) { currentcontact.Name = NametxtBx.Text; currentcontact.PhoneNumber = PhonetxtBx.Text; Db_Helper.UpdateContact(currentcontact);//Update selected DB contact Id Frame.Navigate(typeof(ReadContactList)); }
4)How to explore my SQLite database data?
Isolated Storage Explorer tool to get the database file.This tool is installed under folder path is Program Files (x86)\Microsoft SDKs\Windows Phone\v8.1\Tools\IsolatedStorageExplorerTool
To use Isolated Storage Explorer, the following things must be true:
- The app that you want to test must be installed on the emulator or device.
- The emulator or device must be running, but the app doesn’t have to be running.
You cannot do the following things with Isolated Storage Explorer:
- You can’t view isolated storage for apps that you’ve installed from the Windows Phone Store.
- You can’t view app settings that are stored in the local folder in Isolated Storage Explorer. These are settings that the app saved by using the IsolatedStorageSettings class.
After that execute following commands from command prompt.
1)First change command prompt directory path to Program Files (x86)\Microsoft SDKs\Windows Phone\v8.1\Tools\IsolatedStorageExplorerTool
2)Get Product Id from project Package.appxmanifest file Packaging Tab under Package name attribute (i.e 9f68177c-0add-437b-8b43-95ec429ee5b5)
3)if your app is run on emulator excute this command: ISETool.exe ts xd 9f68177c-0add-437b-8b43-95ec429ee5b5 c:\data\myfiles
4)if your app is run on device excute this command: ISETool.exe ts de 9f68177c-0add-437b-8b43-95ec429ee5b5 c:\data\myfiles
Now we will be found DB content in your computer at c:\data\myfiles like this.
Note:This content may be change in future.
Summary:
In this article, we have seen the basics of Sqlite, how to install the engine, the library Sqlite-net, and saw the most common operations (also known as code first), such as inserting, updating, and deleting data from a table of a database.
FeedBack Note: Please share your thoughts,what you think about this post,Is this post really helpful for you?otherwise it would be very happy ,if you have any thoughts for to implement this requirement in any another way?I always welcome if you drop comments on this post and it would be impressive.
Follow me always at @Subramanyam_B
Have a nice day by Subramanyam Raju :)
Follow me always at @Subramanyam_B
Have a nice day by Subramanyam Raju :)
This comment has been removed by the author.
ReplyDeleteCheck in 'App.xaml.cs' page,there i declared DB_PATH static string variable.
DeleteThanks for the article!
ReplyDeleteDo you an accompanying C# WP8.1 project one can download?
Please click on 'Download Code' from bottom of the post,have you seen that...
Deletethanks for the article sir!
ReplyDeleteI want to know how can I import already existing SQLite database in my windows phone 8 application..
I really need your help sir..
Hi Nitin,
DeleteToday i posted about it and please check this link
http://bsubramanyamraju.blogspot.in/2015/02/windowsphone-working-with-exisitng.html
sir, i need to build a chat application for windows phone 8.1 i searched alot but found nothing helped, please help its very urgent.
ReplyDeleteplz reply at:
shaikhfk@ymail.com
Hi,
ReplyDeleteI have got my SQlite DB by follwoing you guidence - Thanks. Now When I run my app in emulator and change something in DB, the DB which I have got in the previous step(Inside IsolatedStore folder) is not being updated. Why is Both are synched(Emulator DB and DB inside IsolatedStore folder) automatically?. Even I have tried to run your commands once again when my App was running it gives me error saying that the DB is currently is used by other program. What Should I if i want to View the Data being accessed/modifed by Emulator Application.
Thanks.
Ilaiyaraja.
After updating DB , stop debug mode and also close opened sqlitemanager, Finally once again run commands
DeleteC:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Tools\IsolatedStorageEx
ReplyDeleteplorerTool>ISETool.exe ts xd 7DFF43A5-29E1-4D3D-9A94-3A0735FD9597 C:DATA\myfiles
Error: Access to the path 'Shared' is denied.
and giving error file not found how to solve this?
Quick question? Could you please provide the readallcontactslist.cs code? Thanks
ReplyDeleteAnd your work is amazing
DeleteHi, need some help please,
ReplyDeleteI'm using your source code to help me to dev my exercice application, firstly, how to insert information to the database like an example contact on loading application without inserting a new one on app loading? secondly, how to show database on an ComboBox, like an user categories example (Xaml and CS)? I'm new in developping Windows phone app so I need some help from you.. Thanks
This comment has been removed by the author.
ReplyDeleteHi, we are the leading developers of mobile event apps. Thanks for sharing this article. I have read your informative post it contains alot of technical points which are good for young developers...
ReplyDeleteWhat is DB_PATH???
ReplyDeleteDear SubramanyamRaju
ReplyDeleteI have some problems with sqlite and joins queries. the query retrieve me all files that I expected, but all of them are empty
Could you send me a small sample of how to do that?
Regards
This comment has been removed by the author.
ReplyDeleteHI
ReplyDeleteIt i svery good article. Easy to understand the SQLite integration,
Keep it up
HI
ReplyDeleteIt i svery good article. Easy to understand the SQLite integration,
Keep it up
Hi,
ReplyDeleteHow can i create database and table from web api in json format and use that data in app
how to fire select query to get data from multiple tables .please provide tutorial on that it will be very usefull
ReplyDeleteHi,
ReplyDeleteCan u please tell me how to manage the CRUD operations in multi threaded WP8.1 RT app as I am getting an error "DataBase is locked".
I same get this error when multi access.
DeleteHi, I am new to windows phone 8 development. Kindly give an idea about the class ReadAllContactsList.cs as i didnt find one.
ReplyDeleteHi,
ReplyDeletePlease let me know how can I store image in SQLite data base.
I got image by using fileopenpicker and want to save image path in SQLite data base. But I'm not able to get image by that path..
Please have a look at this question.
http://stackoverflow.com/questions/32679519/get-path-of-selected-image-by-fileopenpicker-windows-phone-8-1-c-sharp
Hi, thanks for the app, it's a very good example.
ReplyDeleteI have a question, two apps can access the same database? Is this posible?
Thank you subbu. Its very easy to understand.
ReplyDeletecan u add comments with the code .. it will be more easy for beginners , i really want to understand this as my final project is on windows phone app. please help me out i ll be greatly thankful
ReplyDeletecan u add comments with the code .. it will be more easy for beginners , i really want to understand this as my final project is on windows phone app. please help me out i ll be greatly thankful
ReplyDeleteThank you, very informative and to the point
ReplyDeleteI recently came accross your blog and have been reading along.I have enjoyed reading. Nice blog.
ReplyDeleteBelfast SEO Companies & iPhone Game Development Belfast UK
Hi, I follow your instruction but getting this error in Visual studio 2015, windows phon 8.1,
ReplyDeleteAdditional information: Unable to load DLL 'sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E).
Could you please provide the ReadAllContactsList.cs code? Thanks
ReplyDeleteYou can download his whole project here: https://code.msdn.microsoft.com/windowsapps/WindowsPhone-8-SQLite-96a1e43b
DeleteHello Subbu .B! Very nice tutorial, congrats! Now i need something more for my Diploma Work. Can you share an example with more than one table. Аfter all searching, I noticed that many people are looking for the same. Could you help me with this please? For example one more table with 'City', so the user can add data only for 'New York' etc.
ReplyDeleteNice tutorial kindly Provide Same for windows 10 Development..thnx a ton!!
ReplyDeleteI have a quick questions:
ReplyDeleteConsider a scenario, where I have used SQLite in my app. I make the app LIVE on windows store. Now, users have downloaded the respective app and made updates in the CONTACT table.
Question:
1) I have released NEW update to the app. If user UPDATES the app on their phone, would it REFRESH the CONTACT table.
2) Consider there were 6 records when app was launched first time. When I updated the app, I added 2 more records which made 8 records in total. How can i insert these 2 NEW additional records?
Thanks in advance.
WP Developer
Thanks for sharing with us, I have started following a lot of these. Blogs are the best alternative to get info and keep learning about the latest trend. Web design is vital if you want to impress your viewers and grow your business. You can read more about web design from App Development Company
ReplyDeleteCado Magenge
iPad App Development Company
SMO services melbourne
Magento Development Company
This is very helpful site for tally user. I really like your site. You write a lot of good.
ReplyDeleteTally Sales
We at Genesis have the best expertise to provide web designing services, software testing,Internet marketing services, web designing services,data scraping and many more.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteIt's really informative! Thanks for the great article.
ReplyDeleteAt Hvantage Technologies, we are dedicated to providing online solutions: Web design & development, e-commerce solution, web promotion/SEO (search engine optimization ) and website maintenance services for your business. more details you should visit here once: www.hvantagetechnologies.com
Thanks for the post. Please visit this site: Top IT company in India
ReplyDelete