Introduction:
In our daily development,some times we may need to store data and access it for later use.So as developer choice we need to decide "which way is best to store data?" and this decision making would be change based on amount of data to be store.However windowsphone is very good at this case . Because windowsphone is provided following ways to store our application data.
1)IsolatedStorageSettings:It is very very useful for storing some basic application settings like user profile settings,and especially in login application after login successfully app need to be home screen when user again launch the app.
2)IsolatedStorageFile: It is available from "System.IO.IsolatedStorage" namespace to access files.And i am really addicted with this uses ,because it is very handy and simple way to store data.It is enough for most of applications.And no limit to data store but of course you'll get an exception if you run out of space when writing new data, so you have to handle that properly.
3)SQLite:It is very useful to store data in database with structured way, Mmm this concept is covered by this post.And this article covers windowsphone 8 sqlite database.So if you want to implement database application for windowsphone 7,you may helped from this link Sqlite client for Windows Phone 7 and for sample see this post.
Requirements:
To run this sample ,you must install windowsphone 8 sdk or higher sdk from here.
Table of Contents:
Unfortunately SQLite is directly not available in windowsphone devices.And in previously it included lot of hard steps to setup sqlite in windowsphone application.But now we are very happy ,because of 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 three steps only (i.e Installing SQLite for Windows Phone SDK,Installing sqlite-net-wp8 package,Installing sqlite-net package)
1.1)Installing SQLite for Windows Phone SDK:
The first step is installing the SQLite for Windows Phone SDK in the Visual Studio that you are using. To do that, click on TOOLS -> Extensions and Updates -> Online -> Then search for "sqlite for windows phone". It should look like the following picture.
You will be redirected this link .It may not useful for you,but best to read this document.And we need to add this extension to our project like this.
Open Solution explorer,Right click on 'References'=>Choose WindowsPhone=>Extensions =>select 'SQlite for WindowsPhone'=>Press 'Ok'
1.2)Installing sqlite-net-wp8 package:
Now one good news is "sqlite-net-wp8 package" is available on Nuget which is previously not available and i say very thankful to creator "Peter Huene".This is a c++ project can works like mediator between SQLite and our source code. So to install it right click on your project (i.e in my case project name is SQLiteWp8) =>Click on "Manage NuGet Packages" and search for "sqlite-net-wp8" => Click on "Install" button.
Note:if the sqlite-net-wp8 does not use the same version of SQLite for windows phone you will not be able to open the app
1.3)Installing sqlite-net package:
Now we are almost completed SQLite setup.But in addition we need to add sqlite-net package which is available from nuget. Because this package provides two helper classes (SQLite.cs and SQLiteAsync.cs) which are play vital role to perform all SQLite operations.So to install it right click on your project (i.e in my case project name is SQLiteWp8)=> Click on "Manage NuGet Packages" and search for "sqlite-net" => Click on "Install" button.
Remembering Notes:
1)Before you compile you will need to add some conditional compilation constants in the application,otherwise You'll probably get this error message: The type or namespace name 'Community' could not be found.To fix this issue right click on your project =>Choose properties =>Build and set value USE_WP8_NATIVE_SQLITE like this
2)You receive an error cannot find a type or namespace SQLite.Verify you have the conditional constants set. Verify you have added a reference to SQLite.
3)f the sqlite-net-wp8 does not use the same version of SQLite for windows phone you will not be able to open the app
4)"Any CPU" problem:
If you get a warning message as shown below, follow these steps to fix it: Right click on the Solution -> Click on Configuration Properties -> Configuration Manager and change the active solution platform to x86 (If you are using an emulator) or ARM (If you are using a Windows Phone 8 device).
***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 ?
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));// NavigationService.Navigate(new Uri("/Views/ReadContactList.xaml", UriKind.Relative));//after add contact redirect to contact listbox page } else { MessageBox.Show("Please fill two fields");//Text should not be empty } }
- 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
<ListBox BorderBrush="#FF141EE4" Height="auto" BorderThickness="2" MaxHeight="580" Grid.Row="1" x:Name="listBoxobj" SelectionChanged="listBoxobj_SelectionChanged"> <ListBox.ItemTemplate> <DataTemplate> <Grid Background="Gray" Width="480"> <Border BorderBrush="White" BorderThickness="1"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <TextBlock Grid.Row="0" x:Name="NameTxt" TextWrapping="Wrap" Text="{Binding Name}" FontSize="28" Foreground="White"/> <TextBlock Grid.Row="1" x:Name="PhoneTxt" TextWrapping="Wrap" Text="{Binding PhoneNumber}" /> <TextBlock Grid.Row="0" Text=">" FontSize="28" Margin="0,0,35,0" HorizontalAlignment="Right" VerticalAlignment="Center"/> <TextBlock HorizontalAlignment="Right" Margin="0,0,35,0" Grid.Row="3" x:Name="CreateddateTxt" TextWrapping="Wrap" Text="{Binding CreationDate}" /> </Grid> </Border> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
So when page is loaded ,i done like this
C#
private void ReadContactList_Loaded(object sender, RoutedEventArgs e) { ReadAllContactsList dbcontacts = new ReadAllContactsList(); DB_ContactList = dbcontacts.GetAllContacts();//Get all DB contacts 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.
C#
private void AddContact_Click(object sender, RoutedEventArgs e) { NavigationService.Navigate(new Uri("/Views/AddConatct.xaml", UriKind.Relative)); }
When "DeleteAll" button is clicked ,i done like this
C#
private void DeleteAll_Click(object sender, RoutedEventArgs e)
{
DatabaseHelperClass Db_Helper = new DatabaseHelperClass();
Db_Helper.DeleteAllContact();//delete all DB contacts
DB_ContactList.Clear();//Clear collections
listBoxobj.ItemsSource = DB_ContactList;
}
When selected listbox item ,i navigate to "Delete_UpdateContacts.xaml" page for delete/update corresponding contact details on listbox SelectionChanged event like this.
C#
private void listBoxobj_SelectionChanged(object sender, SelectionChangedEventArgs e) {if (listBoxobj.SelectedIndex!= -1) { Contacts listitem = listBoxobj.SelectedItem as Contacts;//Get slected listbox item contact ID NavigationService.Navigate(new Uri("/Views/Delete_UpdateContacts.xaml?SelectedContactID=" + listitem.Id, UriKind.Relative));} }
- Delete_UpdateContacts.xaml:This page is for updating/delete selected contact details
C#
protected override void OnNavigatedTo(NavigationEventArgs e) { Selected_ContactId = int.Parse(NavigationContext.QueryString["SelectedContactID"]); 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.
C#
private void DeleteContact_Click(object sender, RoutedEventArgs e)
{
Db_Helper.DeleteContact(Selected_ContactId);//Delete selected DB contact Id.
NavigationService.Navigate(new Uri("/Views/ReadContactList.xaml", UriKind.Relative));
}
When "Update" button is pressed i done like this.
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 NavigationService.Navigate(new Uri("/Views/ReadContactList.xaml", UriKind.Relative)); }
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.0\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.0\Tools\IsolatedStorageExplorerTool
2)Get Product Id from project WMAppManifest.xml file Packaging Tab under ProductId attribute (i.e 9748984e-2779-41fb-991f-f99c72414203)
3)if your app is run on emulator excute this command: ISETool.exe ts xd 9748984e-2779-41fb-991f-f99c72414203 c:\data\myfiles
4)if your app is run on device excute this command: ISETool.exe ts de 9748984e-2779-41fb-991f-f99c72414203 c:\data\myfiles
Now we will be found DB content in your computer at c:\data\myfiles like this.
Final Step:
After downloaded from the Store you app may not be create database file.So copy your existing database file and paste it into your project root folder by right click your project=> Add Existing Item=>Browse to c:\data\myfiles\ContactsManager.sqlite. In your Application_Launching event of App.xaml check whether database is existing or not.If not exist,then copy the your database file from installed folder to local folder.Thats it will fix the app store issue.
Note:Make sure to change the Copy to Output Directory property of ContactsManager.sqlite file to Copy if newer.
C#
public partial class App : Application { private async void Application_Launching(object sender, LaunchingEventArgs e) { StorageFile MyDBFile = null; try { // Read the db file from DB path MyDBFile = await StorageFile.GetFileFromPathAsync(DB_PATH); } catch (FileNotFoundException) { if (MyDBFile == null) { // Copy file from installation folder to local folder. IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication(); // Create a stream for the file in the installation folder. using (Stream input = Application.GetResourceStream(new Uri("ContactsManager.sqlite", UriKind.Relative)).Stream) { // Create a stream for the new file in the local folder. using (IsolatedStorageFileStream output = iso.CreateFile(DB_PATH)) { // Initialize the buffer. byte[] readBuffer = new byte[4096]; int bytesRead = -1; // Copy the file from the installation folder to the local folder. while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0) { output.Write(readBuffer, 0, bytesRead); } } } } } } }
Visitors Note:This content may be change in future.if you are looking for SQlite sample for windowsphone store 8.1.You may visit this link :)
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 :)
Thanks for Your Great Job in SQLITE FOR WP8
ReplyDeleteThanks prem :)
Deleteamazing ... I wish you could also add android tuts ... wonderful .This site crazily helped me so much.Be blessed
DeletePlease start your blog for Android and iPhone development also we have work in all Mobile platform developments it's my request ... We can do Subbu ....
ReplyDeleteHI prem presently i am only concentrate on WindowsPhone tutorials..Because I am big fan of windowsphone even i am android developer.And now i am full satisfactions with this blog ,I am really thanks to my dear visitors,Because they makes me with lot of encouragement with active role in my blog by asking/requesting sample to be post.However as per your request i was planned to post articles on three platforms(WindowsPhone,Iphone adn Android ).Please see my future blog look like this .But it will be take time to construct that blog.
DeleteYour Upcoming Blog is Fantastic, am proud to be your Follower and as well as Friend and ....... it is very useful to every body who entering into Mobile Technologies ....
DeleteHow to get files from isolated storage.
ReplyDeletehttp://windowsphone-9.blogspot.com/2014/08/how-to-make-free-license-applications.html
After performing all the steps and configuring the platform.
ReplyDeleteyou need to do this :
Right-click References and select add reference.Go to Windows Phone -> Extensions and check the option SQlite for Windows Phone
Hi,
ReplyDeleteIt is a great tutorial. But can you please tell me one thing, how to read the blob data stored in a sqlite table?. I have kept the column as byte array in the class. But looks like it does not returning the correct value.
Class:
public class TableDetails
{
public byte[] blob_field { get; set; }
}
I have executed like this:
var sqlResult = await db.QueryAsync("SELECT blob_field FROM table_name");
Is there any way to resolve this by reading database as stream, or something?.
I am very new at windows phone app.
Thanks.
Hi it's really nice tutorial, but I have one error I have red line under DB_ContactList why is that happing how can I solve this problem. many thanks.
ReplyDeleteHi pls put the code for ReadAllContacts.cs file. Its shown in screenshot, but not code is not provided. the following code is throwing error. pls let me know the reason.
ReplyDeleteprivate void ReadContactList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllContactsList dbcontacts = new ReadAllContactsList();
DB_ContactList = dbcontacts.GetAllContacts();//Get all DB contacts
listBoxobj.ItemsSource = DB_ContactList.OrderByDescending(i => i.Id).ToList();//Binding DB data to LISTBOX and Latest contact ID can Display first.
}
Hi,
DeleteAre you sure about inserting alt-east one contact item to database before reading contactlist from database.And you may check source code by downloading this sample.
Hi,
ReplyDeleteYes i have one entry in DB for sure. I inserted using SQLite Manager Client of Firefox. Pls. let me know where i could find code for as suggested by you.
Thanks a lot.. Avi
There is add button for inserting contact into db "AddConatct.xaml" page .Have you found it?
DeleteWhere is the source code to download for this project?
ReplyDeleteDownload from here http://code.msdn.microsoft.com/windowsapps/WindowsPhone-8-SQLite-96a1e43b
Deletethanks
DeleteHi subbu,
ReplyDeletecan you please provide the tutorial on using sql lite for windows phone 8.1.
I need to understand the basic before implementing the same
Thanks
richa
Ya sure,very soon i will be post it :)
DeleteHi please check this WindowsPhone 8.1 SQLite: How to Store Data in DataBase for Beginners Tutorial(C#-XAML)
DeleteHow did you created ContactManager.sqlite...
ReplyDeleteDownload source code and check 'ContactManager.sqlite' file name in App.xaml.cs.
Deletehow did you create the file ContactManager.sqlite?
ReplyDeletewhen I run it I get this exception: System.IO.FileNotFoundException.
could someone help me?
Download source code and check 'ContactManager.sqlite' file name in App.xaml.cs,And also please check STEP 1.1 ,we need to add sqlite extension to our project like this.
DeleteOpen Solution explorer,Right click on 'References'=>Choose WindowsPhone=>Extensions =>select 'SQlite for WindowsPhone'=>Press 'Ok'.
Generally in this sample 'System.IO.FileNotFoundException.' error occurs when we did not reference the sqlite extension to our project.
thank alot man
ReplyDeleteput your code in this blog that write plez>>
Hi,
ReplyDeleteHow to encrypt and decrypt sqlite database in windows phone 8.1
Thanks,
Alok
Where is source code?
ReplyDeletePlease click on 'Download Code' from bottom of the post,have you seen that...It will be redirect to source code page.
DeleteVery useful Tutorial..
ReplyDeleteDatabase Agency list
Email and Mobile Database
How to do database update for new versions , without effecting the old users. please tell me.
ReplyDeleteNice work...How to do Select count and then i have to insert values depends on count..Any suggestions..
ReplyDeleteGreat artical Subbu...Thank you.
ReplyDeleteI had a small doubt.... I am developing a app that needs more data (Tables) predefined and I need to retrieve data from them.... Is there any solution like sqlserver where we can create tables and insert data and we can use that tables in our app directly by the DB connection.... Plz help me ... I am so confused.... :(
ReplyDeleteExellent article! Thanx
ReplyDeleteBest Hidden Android Secret Codes 2015 => http://topcellsmartphone.com/best-hidden-android-secret-codes/
ReplyDeleteCan you show me how to store(insert, select update) XML file to(from) SD Card, Please!
ReplyDeleteSo, Is this code helps me to create an application library (books) ?!
ReplyDeleteUseful one but can you make it with best practice coding standard. Please..please
ReplyDeleteHow can I read the contacts and edit the phone numbers?In Brazil it is adding another digit in phone numbers.I would like to develop this feature. Thank you.
ReplyDeletecan anyone please elaborate on the part for downloading database file from emulator to computer I dint got it.
ReplyDeleteAwesome windows phone post
ReplyDeleteHae Subbub, I have used your tutorial and it has helped me so much. However, after submitting my app to the windows phone store, it never passed certification. They are giving me this issue, the application is exiting on launch. I copied the database to the root folder of my project aand copied if newer. My question was, how can I test whether my database on the root folder is working or not?
ReplyDeleteHello Subramanyam Raju,
ReplyDeleteThis is fantastic tutorial. But i have one issue. Please Help me.
I am begginer in windows phone technology. I have one issue found on sqllite integration
Error: Unable to load DLL 'sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
I am waiting your response.
thanks a lot bosss............
ReplyDeletereally nice article !!! I had learned so many things reading this article, thanks a lot for sharing the information. Our site also provides an innovative and interactive Mobile App Services and if you want more ideas to refer our site: www.hvantagetechnologies.com
ReplyDelete