Google Universal apps :How to store list of objects into Local Application Storage (C#-Xaml) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Sunday, 23 August 2015

Universal apps :How to store list of objects into Local Application Storage (C#-Xaml)


Introduction:

In previous article, I was explained about 'How to store list of items into IsolatedStorage in silver light apps'. Now we can learn 'how to store list of objects in universal app?' and also this article will teach you about following topics:
1. Why we need to store data?
2. What is StorageFile?
3. How to store list of items in StorageFile?
4. How to read list of items from StorageFile?

Requirements:

  • This sample is targeted for universal app,Make sure you’ve downloaded and installed SDK  from here.
  • 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.

Description:

1. Why we need to store data?
In every mobile app, we may need to store our data in local application data storage and access it for later use. In Universal apps, the developer has the ability to save user data and also we can fetch data from it when user again launch the app.
2. What is StorageFile?
The data stored in StorageFile is saved even when an application is not in running mode and you can also fetch data from it when running the app again.

3. How to store list of items in StorageFile?

Step 1:

1)Open Microsoft Visual Studio Express 2013 for Windows.
2)Create new Universal project using the "Blank App" template available under Visual C# -> Store Apps -> Universal Apps. (for example project name :DataStoring)


And solution explorer should be like this: 


Step 2:

For making common page for windowsphone & windows store, here I am moving MainPage  to  Shared section and trying to add following xaml code: 



<Page 
    x:Class="DataStoring.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="using:LaunchPad" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
 
    <Grid> 
        <Grid x:Name="grid1"> 
            <Grid.RowDefinitions > 
                <RowDefinition Height="Auto"/> 
                <RowDefinition Height="*"/> 
            </Grid.RowDefinitions> 
            <Grid.ColumnDefinitions> 
                <ColumnDefinition Width="*"/> 
            </Grid.ColumnDefinitions> 
            <Grid Background="#FFA0E2AC" Grid.Row="0"> 
                <Grid.ColumnDefinitions> 
                    <ColumnDefinition Width="6*"/> 
                    <ColumnDefinition Width="*"/> 
                </Grid.ColumnDefinitions> 
                <Image Grid.Column="1" Stretch="Uniform" Height="56" Width="56"  
Source="Common/Images/Settings.png" VerticalAlignment="Top" HorizontalAlignment="Right"
  Tapped="settingsImage_Tap"/> 
                <ComboBox  Margin="12,0,0,0" HorizontalAlignment="Stretch" 
BorderBrush="Aqua"  ItemsSource="{Binding objUrlsList}" Grid.Row="0" x:Name="comboBoxUrls"  
SelectionChanged="ComboBox_SelectionChanged"> 
                    <ComboBox.ItemTemplate> 
                        <DataTemplate> 
 
                            <TextBlock Text="{Binding UrlName}"/> 
                        </DataTemplate> 
                    </ComboBox.ItemTemplate> 
                </ComboBox> 
            </Grid> 
            <Grid Grid.Row="1"  Style="{StaticResource LayoutGridStyle}"> 
                <WebView x:Name="WebView1" HorizontalAlignment="Left" VerticalAlignment="Top" /> 
                <ProgressRing x:Name="progressRing1" IsActive="True" Height="60" Width="60"  
Background="Transparent"/> 
            </Grid> 
        </Grid> 
    </Grid> 
</Page>
Step 3: Right click on DataStoring.Shared section and create new folder name is 'Common' and add below class name is WebUrls.cs


using System; 
using System.Collections.Generic; 
using System.Text; 
 
namespace DataStoring.Common
{ 
    public class WebUrls 
    { 
        public string Url_ID { getset; } 
        public string UrlName { getset; } 
    } 
}
And now solution explorer should be like this:




Step 4:
Now store list of items into storage file.



public async void SaveListofUrls() 
        { 
            List<WebUrls> objUrlsList = new List<WebUrls>(); 
            objUrlsList.Add(new WebUrls { Url_ID = "1", UrlName = "http://bing.com" }); 
            objUrlsList.Add(new WebUrls { Url_ID = "0", UrlName = "http://microsoft.com" }); 
            objUrlsList.Add(new WebUrls { Url_ID = "2", UrlName = "http://bsubramanyamraju.blogspot.in/" }); 
 
            StorageFile userdetailsfile = await ApplicationData.Current.LocalFolder.CreateFileAsync
("MyList", CreationCollisionOption.ReplaceExisting); 
 
            IRandomAccessStream raStream = await userdetailsfile.OpenAsync(FileAccessMode.ReadWrite); 
 
            using (IOutputStream outStream = raStream.GetOutputStreamAt(0)) 
            { 
 
                // Serialize the Session State. 
 
                DataContractSerializer serializer = new DataContractSerializer(typeof(List<WebUrls>)); 
 
                serializer.WriteObject(outStream.AsStreamForWrite(), objUrlsList); 
 
                await outStream.FlushAsync(); 
                outStream.Dispose(); //  
                raStream.Dispose();             } 
        }
 


 In above code first I added list of items and  stored in new storage file name is 'MyList'.

Step 5:
Read list of items from storage file:
public async void readListofUrls() 
        { 
            List<WebUrls> objUrlsList = new List<WebUrls>(); 
 
            var Serializer = new DataContractSerializer(typeof(List<WebUrls>)); 
            using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("MyList")) 
            { 
                objUrlsList = (List<WebUrls>)Serializer.ReadObject(stream); 
            } 
            comboBoxUrls.ItemsSource = objUrlsList; 
            comboBoxUrls.SelectedIndex = 0; 
        }
 In above code, I am trying retrieve data from storage file name is 'MyList" and
 binding the list to comboBox.

Sample screens:



 LocalStorage

FeedBack Note:
Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)

2 comments:

  1. Hi Subbu,

    Very well explained man. But sometimes i'm getting exception 'Unexpected end of file.' while calling GetTypeItemList().

    Here is my code. Please let me know where i'm doing wrong.

    public async void SaveTypeItemList(ObservableCollection objItemList)
    {
    try
    {
    StorageFile userdetailsfile = await ApplicationData.Current.LocalFolder.CreateFileAsync(_selectedType + "ItemList", CreationCollisionOption.ReplaceExisting);
    IRandomAccessStream raStream = await userdetailsfile.OpenAsync(FileAccessMode.ReadWrite);
    using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
    {
    DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection));
    serializer.WriteObject(outStream.AsStreamForWrite(), objItemList);
    await outStream.FlushAsync();
    outStream.Dispose();
    raStream.Dispose();
    }
    }
    catch { }
    }
    public async Task> GetTypeItemList()
    {
    ObservableCollection objItemList = new ObservableCollection();
    try
    {
    var Serializer = new DataContractSerializer(typeof(ObservableCollection));
    using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(_selectedType + "ItemList"))
    {
    objItemList = (ObservableCollection)Serializer.ReadObject(stream);
    }
    }
    catch { }
    return objItemList;
    }

    ReplyDelete
  2. This article is very much helpful and i hope this will be an useful information for the needed one. Keep on updating these kinds of informative things...
    ios App Development Company
    Mobile App Development Company

    ReplyDelete

Search Engine Submission - AddMe