Documente Academic
Documente Profesional
Documente Cultură
Contents
Introduction .................................................................................................................................................. 3
Working with Key-Value Pairs ....................................................................................................................... 4
Creating 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
Page | 2
Introduction
Welcome 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 Hints that will help make it easier for you to transition your
existing skills to the Windows platform. Youll also see some Visual Studio Tips to 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 the Android to Windows Phone 8 Building Your First App tutorial.
Good luck!
Page | 3
ANDROID HINT
The SharedPreferences class in Android is similar to the IsolatedStorageSettings class in Windows
Phone apps.
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.
ANDROID HINT
In Android you can create preference files using MODE_WORLD_READABLE and
MODE_WORLD_WRITEABLE which 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.
Page | 4
To create a similar key-value pair in a Windows Phone app you would write the following:
var localSettings = IsolatedStorageSettings.ApplicationSettings;
localSettings.Add("Name", "Me");
To perform a similar operation on the settings store in a Windows Phone app you would write:
var localSettings = IsolatedStorageSettings.ApplicationSettings;
string nameValue = (string) localSettings["Name"];
localSettings.Remove("Name");
Page | 5
Creating a File
To create a file called hello.txt in Android, you would write code similar to the following:
String filename = "hello.txt";
String string = "Hello world!";
FileOutputStream outputStream;
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
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.
To create the same file in a Windows Phone app you leverage the StorageFile class and the Stream class.
string text = "Hello world!";
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(text.ToCharArray());
StorageFile file = await
Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("Hello.txt",
CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenStreamForWriteAsync())
{
stream.Write(fileBytes, 0, fileBytes.Length);
}
Reading a File
To read the content of the hello.txt file in Android you leverage the BufferedReader class.
String filename = "hello.txt";
BufferedReader reader = new BufferedReader(new FileReader(filename));
String currentLine = null;
Android to Windows Phone 8 Working with Data
Page | 6
Deleting a File
To delete a file called hello.txt in Android you simply instantiate a File object using the path to the file
and call its delete method.
String filename = "hello.txt";
File file = new File(filename);
file.delete();
In Windows Phone you do something very similar. The main difference being you first need to get a
reference to the folder the file is in.
string filename = "Hello.txt";
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile file = await local.GetFileAsync(filename);
await file.DeleteAsync();
Page | 7
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 Tools menu, then click Extensions and Updates
2. In the tree on the left of the Extensions and Updates window, click Online, then click Visual
Studio Gallery.
3. Next, type sqlite in the search box in the upper right hand corner and press Enter.
4. The SQLite for Windows Phone package should appear. Click Download.
Page | 8
6. Once the package is installed you will need to restart Visual Studio
Page | 9
ANDROID HINT
The SQLite for Windows Package package is similar to the android.database.sqlite package.
2. In the tree on the left hand side of the Reference Manager windows, expand the Windows
Phone and the Extensions nodes.
3. Then select both the SQLite for Windows Phone and click OK.
4. You should now see the extension appear under the References folder for you project.
Page | 10
2. Expand the Online node 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.
Page | 11
5. Two source files will be added to your project: SQLite.cs and SQLiteAsync.cs.
6. If you look in your Error List youll see a number of errors. This is due the fact that sqlite-net is
dependent on csharp-sqlite which has not been ported to Windows Phone 8.
Page | 12
7. To work around this youll need to use the sqlite-net-wp8 native C++ project. Youll first need to
go to the projects repository on github and download the zip version of the repository.
8. Right-click the downloaded zip file, click Properties, click Unblock, and click OK.
Page | 13
11. In the Add Existing Project dialog, brose to the location where you unzipped the content in step,
select the Sqlite.vcxproj file, and click Open.
Page | 14
12. You should now see the Sqlite project in your solution.
13. You now need to add a reference to the Sqlite project to your Windows Phone project. Rightclick the References folder of your Windows Phone project and click Add
Page | 15
14. In the Reference Manager dialog select Solution from the tree on the left-had side, select
Projects.
15. Check the box next to the Sqlite project 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
Page | 16
17. Click Build and add the following to the conditional compilation symbols text box:
;USE_WP8_NATIVE_SQLITE
Page | 17
18. Build your solution by pressing F6. You should now see a Build succeeded message 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-net package
you obtained in the last section, you can define the table by simply writing a class.
public class Post
{
[PrimaryKey]
public int Id { get; set; }
public string Title { get; set; }
public string Text { 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.
Android to Windows Phone 8 Working with Data
Page | 18
Once the table is defined it needs to be created, which can be done like this:
private async void CreateTable()
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
await conn.CreateTableAsync<Post>();
}
The blog parameter in the constructor for the SQLiteAsyncConnection class simply specifies the path
to the SQLite database.
The Post type specified in the call to the CreateTableAsync method specifies the type of table that
should be created. This maps back to the Post class created earlier.
ANDROID HINT
In Android you would create a table that extends the SQLiteOpenHelper class that contains the
following method:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Post ( Id INTEGER PRIMARY KEY, Title TEXT, Text TEXT
)");
}
Inserting a Record
Now that the table is created, records can be added to it with the following code:
public async void InsertPost(Post post)
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
await conn.InsertAsync(post);
}
ANDROID HINT
In Android you could insert the record with the following code:
public void insertPost(SQLiteDatabase db, String title, String text ) {
ContentValues values = new ContentValues();
values.put("Title", title);
values.put("Text", text);
long newRowId;
newRowId = db.insert("Post", null, values);
}
Retrieving Records
Retrieve all records from the table with the following:
Android to Windows Phone 8 Working with Data
Page | 19
ANDROID HINT
In Android you could return a Cursor object containing all records using the following:
public Cursor getPosts(SQLiteDatabase db){
String[] projection = {"Id", "Title", "Text" };
Cursor c = db.query(
"Post",
projection,
null,
null,
null,
null,
null
);
return c;
}
Page | 20
ANDROID HINT
The following will retrieve a single record in Android:
public Cursor getPost(SQLiteDatabase db, Integer id){
String[] projection = {"Id", "Title", "Text" };
String selection = "Id LIKE ?";
String[] selelectionArgs = { String.valueOf(id) };
Cursor c = db.query(
"Post",
projection,
selection,
selectionArgs,
null,
null,
null
);
return c;
}
Page | 21
Updating a Record
Updating a record requires the following code:
public async void UpdatePost(Post post)
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
await conn.UpdateAsync(post);
}
ANDROID HINT
In Android you could update the record with the following code:
public void updatePost(SQLiteDatabase db, Integer id, String title, String text ) {
ContentValues values = new ContentValues();
values.put("Title", title);
values.put("Text", text);
String selection = "Id LIKE ?";
String[] selelectionArgs = { String.valueOf(id) };
int count = db.update(
"Post,
values,
selection,
selectionArgs);
}
Deleting a Record
A record can be delete with the following:
public async void DeletePost(Post post)
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
await conn.DeleteAsync(post);
}
Page | 22
ANDROID HINT
In Android you could delete the record with the following code:
public void deletePost(SQLiteDatabase db, Integer id ) {
String selection = "Id LIKE ?";
String[] selelectionArgs = { String.valueOf(id) };
db.delete("Post", selection, selectionArgs);
}
Page | 23
Conclusion
In 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.
Page | 24
Saving Files
Page | 25