×
Namespaces

Variants
Actions
(Difference between revisions)

Saving application preferences in Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search
kiran10182 (Talk | contribs)
m (Kiran10182 -)
hamishwillee (Talk | contribs)
m (Text replace - "[[Category:Silverlight" to "[[Category:XAML")
(15 intermediate revisions by 4 users not shown)
Line 1: Line 1:
[[Category:Windows Phone]][[Category:Silverlight]]
+
[[Category:Windows Phone]][[Category:XAML]][[Category:Code Snippet]][[Category:Files/Data]][[Category:Application Framework]][[Category:Windows Phone 7.5]]
{{Abstract|This article explains how to save and load application preferences on Windows Phone 7 devices. }}  
+
{{Abstract|This article explains how to save and load application preferences using [http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings(v=vs.95).aspx IsolatedStorageSettings] on Windows Phone 7.5. }}
{{ArticleMetaData <!-- v1.1 -->
+
{{SeeAlso|
 +
*[http://msdn.microsoft.com/en-us/library/cc221360(v&#61;vs.95).aspx How to: Store and Retrieve Application Settings Using Isolated Storage] (MSDN)
 +
* [[Introduction and best practices for IsolatedStorageSettings]]
 +
* [[File manipulation with IsolatedStorageFile on Windows Phone]]
 +
}}
 +
{{ArticleMetaData <!-- v1.2 -->
 
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
 
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
|devices= 'Nokia Lumia 800
+
|devices= Nokia Lumia 800
 
|sdk= <!-- SDK(s) built and tested against (e.g. [http://linktosdkdownload/ Qt SDK 1.1.4]) -->
 
|sdk= <!-- SDK(s) built and tested against (e.g. [http://linktosdkdownload/ Qt SDK 1.1.4]) -->
|platform= <!-- Compatible platforms - e.g. Symbian^1 and later, Qt 4.6 and later -->
+
|platform= Windows Phone 7.5
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->  
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|signing=<!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
+
|signing= <!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
|keywords= IsolatedStorageSettings -->
+
|keywords= IsolatedStorageSettings
|id= <!-- Article Id (Knowledge base articles only) -->
+
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|translated-by= <!-- [[User:XXXX]] -->
 
|translated-by= <!-- [[User:XXXX]] -->
|translated-from-title= <!-- Title only -->  
+
|translated-from-title= <!-- Title only -->
 
|translated-from-id= <!-- Id of translated revision -->
 
|translated-from-id= <!-- Id of translated revision -->
|review-by=<!-- After re-review: [[User:username]] -->
+
|review-by= <!-- After re-review: [[User:username]] -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-by= <!-- After significant update: [[User:username]]-->
Line 26: Line 30:
  
 
== Introduction ==
 
== Introduction ==
In most applications, saving user preferences is a common task. Common scenarios can be - Saving user's country in applications like Groupon, saving and loading top scores in games, saving user's preferences for sounds in a game.
+
Saving user preferences is a common task requirement for applications. Common scenarios include saving the user's country, top scores in games, game sounds, login ids etc.
This articles discusses the procedure to save and load such user preferences.
+
  
== Class ==
+
This articles discusses the procedure to save and load such user preferences using [http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings(v=vs.95).aspx IsolatedStorageSettings] class. It provides a dictionary-like, key-value store which is preserved across device reboots. The settings are securely stored inside the Isolated Storage space of an application, and are inaccessible to other applications.
The class [http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings(v=vs.95).aspx IsolatedStorageSettings] comes to our rescue to save and load these preferences. The class helps you store dictionary-like, key-value store. IsolatedStorageSettings are preserved across device reboots. The settings are stored inside the Isolated Storage space of an application, hence inaccessible to other applications. Hence, we can claim they are secure.
+
  
== Sample Application ==
+
In order to work best with the application life-cycle we load and save the settings when the settings page is loaded.
 +
 
 +
== Sample application ==
  
 
Below, we create a simple application that stores the user's preferences in a game. Three elements such as Game Music, Timed Mode and Difficulty level have been identified as preferences for a game.
 
Below, we create a simple application that stores the user's preferences in a game. Three elements such as Game Music, Timed Mode and Difficulty level have been identified as preferences for a game.
 
Since Game Music and Timed Mode essentially hold boolean values, in the UI of application we use ToggleSwitch. ToggleSwitch does not come along with the Windows Phone SDK and has to be downloaded separately from codeplex and installed. This has been described [http://www.codebadger.com/blog/post/2010/10/28/WP7-Development-Tip-of-the-Day-Silverlight-Toolkit-for-Windows-Phone.aspx here]. This is rich resource for Windows Phone controls. Lets create the user interface for the settings page in XAML.
 
Since Game Music and Timed Mode essentially hold boolean values, in the UI of application we use ToggleSwitch. ToggleSwitch does not come along with the Windows Phone SDK and has to be downloaded separately from codeplex and installed. This has been described [http://www.codebadger.com/blog/post/2010/10/28/WP7-Development-Tip-of-the-Day-Silverlight-Toolkit-for-Windows-Phone.aspx here]. This is rich resource for Windows Phone controls. Lets create the user interface for the settings page in XAML.
  
<code csharp>
+
<code xml>
 
<phone:PhoneApplicationPage  
 
<phone:PhoneApplicationPage  
 
     x:Class="Pref.MainPage"
 
     x:Class="Pref.MainPage"
Line 77: Line 81:
 
         </Grid>
 
         </Grid>
 
     </Grid>
 
     </Grid>
 
    <!--Sample code showing usage of ApplicationBar-->
 
    <!--<phone:PhoneApplicationPage.ApplicationBar>
 
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
 
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
 
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
 
            <shell:ApplicationBar.MenuItems>
 
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
 
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
 
            </shell:ApplicationBar.MenuItems>
 
        </shell:ApplicationBar>
 
    </phone:PhoneApplicationPage.ApplicationBar>-->
 
 
 
</phone:PhoneApplicationPage>
 
</phone:PhoneApplicationPage>
  
Line 95: Line 86:
  
  
This gives us an interface like this.
+
Above code gives us an UI interface like this.
  
 
[[File:One.png|300px|Application UI]]
 
[[File:One.png|300px|Application UI]]
  
 
== Code Behind ==
 
== Code Behind ==
Instead of having a save and load button on the UI, it is more intuitive to simply load and save preferences when the user navigates TO and FROM the page. Hence in the MainPage.xaml.cs Class, we override the OnNavigatedTo() and OnNavigatedFrom() methods.
+
Instead of having a save and load button on the UI, it is more intuitive to simply load and save preferences when the user navigates TO and FROM the page. Hence in the MainPage.xaml.cs Class, we override the {{Icode|OnNavigatedTo()}} and {{Icode|OnNavigatedFrom()}} methods.
  
 
<code csharp>
 
<code csharp>
Line 150: Line 141:
 
</code>
 
</code>
  
So as you can observe, I am accessing the values in the IsolatedStorageSettings in the form of Key Value pairs. Remember to cast the values when retrieving or saving to this file. It is also reminded that Save() method needs to be called to store or flush these values. If a key is non-existent in the IsolatedStorageSettings, then it may raise KeyNotFoundException.  
+
So as you can observe, I am accessing the values in the {{Icode|IsolatedStorageSettings}} in the form of Key Value pairs. Remember to cast the values when retrieving or saving to this file. It is also reminded that {{Icode|Save()}} method needs to be called to store or flush these values. If a key is non-existent in the {{Icode|IsolatedStorageSettings}}, then it may raise {{Icode|KeyNotFoundException}}.  
 
+
 
+
 
== Summary ==
 
== Summary ==
 
This article describes one of the fundamental tasks in application development - saving and loading user preferences. This is can be extended to many minimal storage use-cases such as top scores in games.  
 
This article describes one of the fundamental tasks in application development - saving and loading user preferences. This is can be extended to many minimal storage use-cases such as top scores in games.  
  
== Further Reading ==
+
== Further reading ==
1. [http://msdn.microsoft.com/en-us/library/cc221360(v=vs.95).aspx How to: Store and Retrieve Application Settings Using Isolated Storage]
+
# [http://msdn.microsoft.com/en-us/library/cc221360(v=vs.95).aspx How to: Store and Retrieve Application Settings Using Isolated Storage]
 
+
# [http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings(v=vs.95).aspx IsolatedStorageSettings class]
2. [http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings(v=vs.95).aspx IsolatedStorageSettings class]
+

Revision as of 04:29, 10 April 2013

This article explains how to save and load application preferences using IsolatedStorageSettings on Windows Phone 7.5.

WP Metro Icon File.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Tested with
Devices(s): Nokia Lumia 800
Compatibility
Platform(s): Windows Phone 7.5
Windows Phone 8
Windows Phone 7.5
Article
Keywords: IsolatedStorageSettings
Created: manikantan (30 Jan 2012)
Last edited: hamishwillee (10 Apr 2013)

Contents

Introduction

Saving user preferences is a common task requirement for applications. Common scenarios include saving the user's country, top scores in games, game sounds, login ids etc.

This articles discusses the procedure to save and load such user preferences using IsolatedStorageSettings class. It provides a dictionary-like, key-value store which is preserved across device reboots. The settings are securely stored inside the Isolated Storage space of an application, and are inaccessible to other applications.

In order to work best with the application life-cycle we load and save the settings when the settings page is loaded.

Sample application

Below, we create a simple application that stores the user's preferences in a game. Three elements such as Game Music, Timed Mode and Difficulty level have been identified as preferences for a game. Since Game Music and Timed Mode essentially hold boolean values, in the UI of application we use ToggleSwitch. ToggleSwitch does not come along with the Windows Phone SDK and has to be downloaded separately from codeplex and installed. This has been described here. This is rich resource for Windows Phone controls. Lets create the user interface for the settings page in XAML.

<phone:PhoneApplicationPage 
x:Class="Pref.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:toolbox="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
 
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
 
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY GAME" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Settings" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
 
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
 
<toolbox:ToggleSwitch Name="gameMusic" Header="Game Music"></toolbox:ToggleSwitch>
<toolbox:ToggleSwitch Name="timed" Header="Timed Mode" Margin="6,119,6,371"></toolbox:ToggleSwitch>
 
<Slider Height="84" HorizontalAlignment="Left" Margin="12,310,0,0" Name="slider1" VerticalAlignment="Top" Width="418" Value="1" Minimum="1" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,274,0,0" Name="Difficulty" Text="Difficulty Level" VerticalAlignment="Top" Width="135" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>


Above code gives us an UI interface like this.

Application UI

Code Behind

Instead of having a save and load button on the UI, it is more intuitive to simply load and save preferences when the user navigates TO and FROM the page. Hence in the MainPage.xaml.cs Class, we override the OnNavigatedTo() and OnNavigatedFrom() methods.

namespace Pref
{
public partial class MainPage : PhoneApplicationPage
{
private IsolatedStorageSettings settings;
// Constructor
public MainPage()
{
InitializeComponent();
settings = IsolatedStorageSettings.ApplicationSettings;
}
 
protected override void OnNavigatedTo(NavigationEventArgs e)
{
System.Diagnostics.Debug.WriteLine("into the app");
try
{
System.Diagnostics.Debug.WriteLine("Retrieving values");
gameMusic.IsChecked = (bool)settings["gamemusic"];
timed.IsChecked = (bool)settings["timed"];
slider1.Value = ( Int16)settings["diff"];
 
}
catch(KeyNotFoundException ex)
{
System.Diagnostics.Debug.WriteLine("First Time using the app");
settings.Add("timed", false);
settings.Add("gamemusic", false);
settings.Add("diff", 1);
settings.Save();
 
}
 
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Exiting, so save now");
settings["timed"] = timed.IsChecked;
settings["diff"] = (Int16) slider1.Value;
settings["gamemusic"] = gameMusic.IsChecked;
settings.Save();
}
}
}

So as you can observe, I am accessing the values in the IsolatedStorageSettings in the form of Key Value pairs. Remember to cast the values when retrieving or saving to this file. It is also reminded that Save() method needs to be called to store or flush these values. If a key is non-existent in the IsolatedStorageSettings, then it may raise KeyNotFoundException.

Summary

This article describes one of the fundamental tasks in application development - saving and loading user preferences. This is can be extended to many minimal storage use-cases such as top scores in games.

Further reading

  1. How to: Store and Retrieve Application Settings Using Isolated Storage
  2. IsolatedStorageSettings class
428 page views in the last 30 days.
×