Android 2 Windows Phone 8 Local Data
-
Upload
anonymous-ubalkko -
Category
Documents
-
view
220 -
download
0
Transcript of Android 2 Windows Phone 8 Local Data
-
8/10/2019 Android 2 Windows Phone 8 Local Data
1/25
ANDROID TO WINDOWS PHONE 8: WORKING WITH DATA
Version 1.0 April 5, 2013
Adam Grocholski
Technical Evangelist | Microsoft
@codel8r|http://thinkfirstcodelater.com
http://twitter.com/codel8rhttp://twitter.com/codel8rhttp://thinkfirstcodelater.com/http://thinkfirstcodelater.com/http://thinkfirstcodelater.com/http://thinkfirstcodelater.com/http://twitter.com/codel8r -
8/10/2019 Android 2 Windows Phone 8 Local Data
2/25
Android to Windows Phone 8Working with Data Page | 2
ContentsIntroduction .................................................................................................................................................. 3
Working with Key-Value Pairs ....................................................................................................................... 4Creating an Application Setting ................................................................................................................ 4
Reading an Application Setting ................................................................................................................. 5
Deleting an Application Setting ................................................................................................................ 5
Working with Files......................................................................................................................................... 6
Creating a File ........................................................................................................................................... 6
Reading a File ............................................................................................................................................ 6
Deleting a File............................................................................................................................................ 7
Working with a SQL Database ....................................................................................................................... 8
Installing SQLite ........................................................................................................................................ 8
Adding a Reference to SQLite ................................................................................................................. 10
Getting Helper Classes ............................................................................................................................ 11
Using SQLite ............................................................................................................................................ 18
Creating a Table .................................................................................................................................. 18
Inserting a Record ............................................................................................................................... 19
Retrieving Records .............................................................................................................................. 19
Updating a Record .............................................................................................................................. 22
Deleting a Record ................................................................................................................................ 22
Conclusion ................................................................................................................................................... 24
Appendix A: Additional Resources .............................................................................................................. 25
-
8/10/2019 Android 2 Windows Phone 8 Local Data
3/25
Android to Windows Phone 8Working with Data Page | 3
IntroductionWelcome to Windows Phone 8 application development! This article assumes you are coming to
Windows with experience developing applications for Android. The purpose of this article is to help you
understand the various ways you can work with data in Windows Phone 8 which include:
Key-Value Sets Files
SQL Database
Along the way youll see some Android Hintsthat will help make it easier for you to transition your
existing skills to the Windowsplatform. Youll also see some Visual Studio Tipsto make you more
productive in your Windows development environment.
This article assumes that you are coming to Windows with experience developing Android applications.
The article also assumes that you have set up your Windows 8 development environment and that you
have built your first application. If you havent done either of these things it is recommended that you
work through theAndroid to Windows Phone 8Building Your First Apptutorial.
Good luck!
http://aka.ms/AndroidToWindowsPhone8http://aka.ms/AndroidToWindowsPhone8http://aka.ms/AndroidToWindowsPhone8http://aka.ms/AndroidToWindowsPhone8http://aka.ms/AndroidToWindowsPhone8http://aka.ms/AndroidToWindowsPhone8 -
8/10/2019 Android 2 Windows Phone 8 Local Data
4/25
Android to Windows Phone 8Working with Data Page | 4
Working with Key-Value PairsIn Android development, if you have a small collection of key-value pairs that you want to persist from
session to session you use the SharedPreferencesAPIs. In Windows Phone development these key-value
pairs are often referred to as Application Settings.
To save or retrieve data as a key-value pair in Windows Phone 8 you use theIsolatedStorageSettingsclass. The IsolatedStorageSettings class is nothing more than a dictionary that enables you to store any
serializable object, such as a string, and is ideally suited for saving small pieces of data. Data stored with
the IsolatedStorageSettings class is persisted in the apps local folder when the app is closed or
deactivated and automatically populated with previously persisted data when the app is launched.
It is important to note that once an application is removed, all of its data stores, including those
associated with settings are deleted from the device.
Lets now look at how you write and read application settings.
Creating an Application Setting
To create a Shared Preference in Android a key of Nameand a value of Me you would write code similar
to the following:
SharedPreferencessharedPref=getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editoreditor=sharedPref.edit();
editor.putString("Name","Me");
editor.commit();
ANDROID HINT
The SharedPreferencesclass in Android is similar to the IsolatedStorageSettingsclass in Windows
Phone apps.
WINDOWS PHONE HINT
Since application settings are tied to the lifetime of the app on a device, you should not use
application settings to store information your users might thing as valuable or irreplaceable. You
should consider using the users libraries or SkyDrive for permanent data.
ANDROID HINT
In Android you can create preference files using MODE_WORLD_READABLEand
MODE_WORLD_WRITEABLEwhich allows other apps that know your file identifier to access you
data. In Windows Phone applications are sandboxed and their settings cannot be accessed by other
apps.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.io.isolatedstorage.isolatedstoragesettings(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/system.io.isolatedstorage.isolatedstoragesettings(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/system.io.isolatedstorage.isolatedstoragesettings(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/system.io.isolatedstorage.isolatedstoragesettings(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/system.io.isolatedstorage.isolatedstoragesettings(v=vs.105).aspx -
8/10/2019 Android 2 Windows Phone 8 Local Data
5/25
Android to Windows Phone 8Working with Data Page | 5
To create a similar key-value pair in a Windows Phone app you would write the following:
varlocalSettings= IsolatedStorageSettings.ApplicationSettings;
localSettings.Add("Name", "Me");
Reading an Application Setting
To retrieve a Shared Preference in Android with a key of Nameand a default value of Me(i.e. the value
returned if the key is not found) you would write the following:
SharedPreferencessharedPref=getActivity().getPreferences(Context.MODE_PRIVATE);
stringnameValue= sharedPref.getString("Name","Me");
To perform a similar operation on the settings store in a Windows Phone app you would write:
varlocalSettings= IsolatedStorageSettings.ApplicationSettings;
stringnameValue= (string) localSettings["Name"];
Deleting an Application SettingTo remove a Shared Preference in Android you use the following code:
SharedPreferencessharedPref=getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editoreditor=sharedPref.edit();
editor.remove("Name");
editor.commit();
To delete a setting from a Windows Phone 8 app you would use:
varlocalSettings= IsolatedStorageSettings.ApplicationSettings;
localSettings.Remove("Name");
WINDOWS PHONE HINT
Do not be tempted to use the LocalSettingsand/or RoamingSettingsproperties of the
ApplicationDataclass in place of the ApplicationSettingsproperty of the IsolatedStorageSettings
class. While the APIs are available, they have not been implemented in Windows Phone 8. An
exception will be thrown if they are called.
-
8/10/2019 Android 2 Windows Phone 8 Local Data
6/25
Android to Windows Phone 8Working with Data Page | 6
Working with FilesWindows Phone allows you to create, read, and delete files on the devices internal storage.
Creating a File
To create a file called hello.txtin Android, you would write code similar to the following:
Stringfilename="hello.txt";
Stringstring="Hello world!";
FileOutputStreamoutputStream;
outputStream=openFileOutput(filename,Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
To create the same file in a Windows Phone app you leverage the StorageFileclass and the Streamclass.
stringtext = "Hello world!";byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(text.ToCharArray());
StorageFilefile = await
Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync( "Hello.txt",CreationCollisionOption.ReplaceExisting);
using(varstream = awaitfile.OpenStreamForWriteAsync()){
stream.Write(fileBytes, 0, fileBytes.Length);}
Reading a File
To read the content of the hello.txtfile in Android you leverage the BufferedReaderclass.
Stringfilename="hello.txt";
BufferedReader reader = new BufferedReader(new FileReader(filename));
String currentLine = null;
ANDROID HINT
In Android to ensure other apps cant read your apps files you have to set its file mode
MODE_PRIVATE. Windows Phone apps run in a sandbox. As a result apps cannot access one anothers
files.
WINDOWS PHONE HINT
Do not be tempted to use the RoamingFolderand/or TemporaryFolderproperties of the
ApplicationDataclass in place of the LocalFolderproperty. While the APIs are available to call, they
have not been implemented in Windows Phone 8. An exception will be thrown if they are called.
-
8/10/2019 Android 2 Windows Phone 8 Local Data
7/25
-
8/10/2019 Android 2 Windows Phone 8 Local Data
8/25
Android to Windows Phone 8Working with Data Page | 8
Working with a SQL DatabaseThere are times when key-value pairs and/or files wont meet your need for data storage. Specifically,
when youre dealing with structured data that is repeated, such as events on a calendar. For this type of
information youll want to use a relational store. This relational store is typically a SQL database. Both
Android and Windows Phone 8 support using the SQLite relational database engine. This section
assumes you have familiarity working with SQLite on Android.
Installing SQLite
The first thing youll need to do is install the SQLite for Windows Phone apps. This can be done by
downloading the SQLite for Windows Phone package
1.
In Visual Studio, click the Toolsmenu, then click Extensions and Updates
2.
In the tree on the left of the Extensions and Updateswindow, click Online, then click Visual
Studio Gallery.
3.
Next, type sqlitein the search box in the upper right hand corner and press Enter.
4.
The SQLite for Windows Phonepackage should appear. Click Download.
-
8/10/2019 Android 2 Windows Phone 8 Local Data
9/25
Android to Windows Phone 8Working with Data Page | 9
5.
You will then be prompted to click Install. Do so.
6.
Once the package is installed you will need to restart Visual Studio
-
8/10/2019 Android 2 Windows Phone 8 Local Data
10/25
Android to Windows Phone 8Working with Data Page | 10
Adding a Reference to SQLite
Now that SQLite is installed you need to add a reference to it from you project.
1.
Right click the References folder in your Windows Phone project and click Add Reference
2.
In the tree on the left hand side of the Reference Managerwindows, expand the Windows
Phoneand the Extensionsnodes.
3.
Then select both the SQLite for Windows Phoneand click OK.
4.
You should now see the extension appear under the Referencesfolder for you project.
ANDROID HINT
The SQLite for Windows Package package is similar to the android.database.sqlitepackage.
-
8/10/2019 Android 2 Windows Phone 8 Local Data
11/25
Android to Windows Phone 8Working with Data Page | 11
Getting Helper Classes
The last thing youll want to do is obtain some helper classes that make working with SQLite a bit easier.
There are a number available for Windows Phone applications. The ones I prefer to use come from the
sqlite-netlibrary.
The sqlite-netlibrary can be obtained from NuGet via the following steps
VISUAL STUDIO TIP
NuGetis a free and open source package manager for the .NET Framework.
1.
Right click on the References folder in you Windows Phone project and click Manage NuGet
Packages
2.
Expand the Onlinenode in the left hand side of the Window.3.
Enter sqlite in the search box in the upper right hand side of Window and press Enter.4.
Select sqlite-net and click Install.
-
8/10/2019 Android 2 Windows Phone 8 Local Data
12/25
Android to Windows Phone 8Working with Data Page | 12
5.
Two source files will be added to your project: SQLite.csand SQLiteAsync.cs.
6.
If you look in your Error Listyoull see a number of errors. This is due the fact that sqlite-netis
dependent on csharp-sqlitewhich has not been ported to Windows Phone 8.
-
8/10/2019 Android 2 Windows Phone 8 Local Data
13/25
Android to Windows Phone 8Working with Data Page | 13
7.
To work around this youll need to use the sqlite-net-wp8 native C++ project. Youll first need to
go to theprojects repository on githuband download the zip version of the repository.
8.
Right-click the downloaded zip file, click Properties, click Unblock, and click OK.
9.
Unzip the content.10.
In the Solution Explorer in Visual Studio, right-click the solution and choose Add, then choose
Existing Project.
https://github.com/peterhuene/sqlite-net-wp8https://github.com/peterhuene/sqlite-net-wp8https://github.com/peterhuene/sqlite-net-wp8https://github.com/peterhuene/sqlite-net-wp8 -
8/10/2019 Android 2 Windows Phone 8 Local Data
14/25
Android to Windows Phone 8Working with Data Page | 14
11.
In theAdd Existing Projectdialog, brose to the location where you unzipped the content in step,
select the Sqlite.vcxprojfile, and click Open.
-
8/10/2019 Android 2 Windows Phone 8 Local Data
15/25
Android to Windows Phone 8Working with Data Page | 15
12.
You should now see the Sqliteproject in your solution.
13.
You now need to add a reference to the Sqliteproject to your Windows Phone project. Right-
click the Referencesfolder of your Windows Phone project and click Add
-
8/10/2019 Android 2 Windows Phone 8 Local Data
16/25
Android to Windows Phone 8Working with Data Page | 16
14.
In the Reference Managerdialog select Solutionfrom the tree on the left-had side, select
Projects.15.
Check the box next to the Sqliteproject and click OK.
16.
The last step is to add a compiler directive to the Windows Phone project. Right-click the
Windows Phone project in Solution Explorer and click Properties
-
8/10/2019 Android 2 Windows Phone 8 Local Data
17/25
Android to Windows Phone 8Working with Data Page | 17
17.
Click Buildand add the following to the conditional compilation symbols text box:;USE_WP8_NATIVE_SQLITE
-
8/10/2019 Android 2 Windows Phone 8 Local Data
18/25
Android to Windows Phone 8Working with Data Page | 18
18.
Build your solution by pressing F6. You should now see a Build succeededmessage and no errors
in the Error List.
Using SQLite
In the last part of this section well look at how to perform some basic tasks with SQLite in your
Windows Phone application.
Creating a Table
The first step youll need to take is to create a table that your application will use. For the sake of
example, lets say your application is storing blog posts in a SQLite table. Using the sqlite-netpackage
you obtained in the last section, you can define the table by simply writing a class.
publicclassPost
{
[PrimaryKey]
publicintId{ get; set; }
publicstringTitle{ get; set; }
publicstringText{ get; set; }
}
The PrimaryKey attributes come from the sqlite-net package. There are a number of attributes that the
package provides that allow you to define the tables schema.
-
8/10/2019 Android 2 Windows Phone 8 Local Data
19/25
Android to Windows Phone 8Working with Data Page | 19
Once the table is defined it needs to be created, which can be done like this:
privateasyncvoidCreateTable()
{
SQLiteAsyncConnectionconn= newSQLiteAsyncConnection("blog");
awaitconn.CreateTableAsync();
}The blogparameter in the constructor for the SQLiteAsyncConnectionclass simply specifies the path
to the SQLite database.
The Posttype specified in the call to the CreateTableAsync method specifies the type of table that
should be created. This maps back to the Postclass created earlier.
Inserting a Record
Now that the table is created, records can be added to it with the following code:
publicasyncvoidInsertPost(Postpost)
{
SQLiteAsyncConnectionconn= newSQLiteAsyncConnection("blog");awaitconn.InsertAsync(post);
}
Retrieving Records
Retrieve all records from the table with the following:
ANDROID HINT
In Android you would create a table that extends the SQLiteOpenHelperclass that contains the
following method:
publicvoidonCreate(SQLiteDatabasedb){db.execSQL("CREATE TABLE Post ( Id INTEGER PRIMARY KEY, Title TEXT, Text TEXT
)");
}
ANDROID HINT
In Android you could insert the record with the following code:
publicvoidinsertPost(SQLiteDatabasedb,Stringtitle,Stringtext){
ContentValuesvalues=newContentValues();
values.put("Title",title);
values.put("Text",text);
longnewRowId;
newRowId=db.insert("Post",null,values);
}
-
8/10/2019 Android 2 Windows Phone 8 Local Data
20/25
Android to Windows Phone 8Working with Data Page | 20
publicasyncTask GetPosts()
{
SQLiteAsyncConnectionconn= newSQLiteAsyncConnection("blog");
varquery= conn.Table();
varresult= awaitquery.ToListAsync();
returnresult;
}
Retrieve a single record from the table with the following:
publicasyncTask GetPost(intid)
{
SQLiteAsyncConnectionconn= newSQLiteAsyncConnection("blog");
varquery= conn.Table().Where(x=> x.Id== id);
varresult= awaitquery.ToListAsync();
returnresult.FirstOrDefault();
}
ANDROID HINT
In Android you could return a Cursor object containing all records using the following:
publicCursorgetPosts(SQLiteDatabasedb){
String[]projection={"Id","Title","Text"};
Cursorc=db.query(
"Post",
projection,
null,
null,
null,
null,
null
);
returnc;
}
-
8/10/2019 Android 2 Windows Phone 8 Local Data
21/25
Android to Windows Phone 8Working with Data Page | 21
ANDROID HINT
The following will retrieve a single record in Android:
publicCursorgetPost(SQLiteDatabasedb,Integerid){
String[]projection={"Id","Title","Text"};
Stringselection="Id LIKE ?";
String[]selelectionArgs={String.valueOf(id)};
Cursorc=db.query(
"Post",
projection,
selection,
selectionArgs,
null,
null,
null
);
returnc;
}
-
8/10/2019 Android 2 Windows Phone 8 Local Data
22/25
Android to Windows Phone 8Working with Data Page | 22
Updating a Record
Updating a record requires the following code:
publicasyncvoidUpdatePost(Postpost)
{
SQLiteAsyncConnectionconn= newSQLiteAsyncConnection("blog");
awaitconn.UpdateAsync(post);}
Deleting a Record
A record can be delete with the following:
publicasyncvoidDeletePost(Postpost)
{
SQLiteAsyncConnectionconn= newSQLiteAsyncConnection("blog");
awaitconn.DeleteAsync(post);
}
ANDROID HINT
In Android you could update the record with the following code:
publicvoidupdatePost(SQLiteDatabasedb,Integerid,Stringtitle,Stringtext){
ContentValuesvalues=newContentValues();
values.put("Title",title);
values.put("Text",text);
Stringselection="Id LIKE ?";String[]selelectionArgs={String.valueOf(id)};
intcount=db.update(
"Post,
values,
selection,
selectionArgs);
}
-
8/10/2019 Android 2 Windows Phone 8 Local Data
23/25
Android to Windows Phone 8Working with Data Page | 23
ANDROID HINT
In Android you could delete the record with the following code:
publicvoiddeletePost(SQLiteDatabasedb,Integerid){
Stringselection="Id LIKE ?";
String[]selelectionArgs={String.valueOf(id)};
db.delete("Post",selection,selectionArgs);}
-
8/10/2019 Android 2 Windows Phone 8 Local Data
24/25
Android to Windows Phone 8Working with Data Page | 24
ConclusionIn this article you learned about the various ways you can work with data in Windows Phone 8 including:
Key-Value Sets
Files
SQL Database
To learn more about building Windows Phone apps continue to follow this series.
-
8/10/2019 Android 2 Windows Phone 8 Local Data
25/25
Appendix A: Additional ResourcesThe table bellows maps Android developer resources fromhttp://developer.android.comto similar
Windows Phone 8 content onhttp://msdn.microsoft.com.
ANDROID RESOURCES WINDOWS PHONE 8 RESOURCES
Saving Data Application Data OverviewSaving Key-Value Sets IsolatedStorageSettings class
Quickstart: Working with settings in Windows Phone
How to create a Settings page for Windows Phone
Saving Files Quickstart: Working with files and folders in Windows Phone 8
Local folder best practices for Windows Phone
Reading from the SD card on Windows Phone 8
How to use the Isolated Storage Explorer tool for Windows Phone
Saving Data in SQL Databases Local database for Windows Phone
SQLite for Windows Phone
http://developer.android.com/http://developer.android.com/http://developer.android.com/http://msdn.microsoft.com/http://msdn.microsoft.com/http://msdn.microsoft.com/http://developer.android.com/training/basics/data-storage/index.htmlhttp://developer.android.com/training/basics/data-storage/index.htmlhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402541(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402541(v=vs.105).aspxhttp://developer.android.com/training/basics/data-storage/shared-preferences.htmlhttp://developer.android.com/training/basics/data-storage/shared-preferences.htmlhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/system.io.isolatedstorage.isolatedstoragesettings(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/system.io.isolatedstorage.isolatedstoragesettings(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/jj714090(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/jj714090(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769510(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769510(v=vs.105).aspxhttp://developer.android.com/training/basics/data-storage/files.htmlhttp://developer.android.com/training/basics/data-storage/files.htmlhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769544(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769544(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/jj720573(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/jj720573(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/hh286408(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/hh286408(v=vs.105).aspxhttp://developer.android.com/training/basics/data-storage/databases.htmlhttp://developer.android.com/training/basics/data-storage/databases.htmlhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202860(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202860(v=vs.105).aspxhttp://visualstudiogallery.msdn.microsoft.com/cd120b42-30f4-446e-8287-45387a4f40b7http://visualstudiogallery.msdn.microsoft.com/cd120b42-30f4-446e-8287-45387a4f40b7http://visualstudiogallery.msdn.microsoft.com/cd120b42-30f4-446e-8287-45387a4f40b7http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202860(v=vs.105).aspxhttp://developer.android.com/training/basics/data-storage/databases.htmlhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/hh286408(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/jj720573(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769544(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698(v=vs.105).aspxhttp://developer.android.com/training/basics/data-storage/files.htmlhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769510(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/jj714090(v=vs.105).aspxhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/system.io.isolatedstorage.isolatedstoragesettings(v=vs.105).aspxhttp://developer.android.com/training/basics/data-storage/shared-preferences.htmlhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402541(v=vs.105).aspxhttp://developer.android.com/training/basics/data-storage/index.htmlhttp://msdn.microsoft.com/http://developer.android.com/