Mahender
Mahender

Reputation: 5664

PhoneApplicationService.Current.State equivalent in windows 8

I am looking for equivalent class in Windows 8.x. API for PhoneApplicationService.Current.State which we found in Windows Phone API.

Basically, I am trying to persist simple object data between pages with in session. Or is there any other option in Windows 8 to achieve this?

Upvotes: 1

Views: 1789

Answers (1)

Martin Suchan
Martin Suchan

Reputation: 10620

I won't recommend using the State, it's much easier to use just IsolatedStorage for preserving data both between sessions and pages as well, to keep is simple.
All data should be saved in ApplicationData.Current.LocalSettings or IsolatedStorageSettings.ApplicationSettings in case they are simple objects like string, bool, int.

// on Windows 8
// input value
string userName = "John";

// persist data
ApplicationData.Current.LocalSettings.Values["userName"] = userName;

// read back data
string readUserName = ApplicationData.Current.LocalSettings.Values["userName"] as string;

// on Windows Phone 8
// input value
string userName = "John";

// persist data
IsolatedStorageSettings.ApplicationSettings["userName"] = userName;

// read back data
string readUserName = IsolatedStorageSettings.ApplicationSettings["userName"] as string;

Complex objects like lists of ints, strings, etc. should be saved in ApplicationData.Current.LocalFolder possibly in JSON format (you need JSON.net package from NuGet):

// on Windows 8
// input data
int[] value = { 2, 5, 7, 9, 42, 101 };

// persist data
string json = JsonConvert.SerializeObject(value);
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("myData.json", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, json);

// read back data
string read = await PathIO.ReadTextAsync("ms-appdata:///local/myData.json");
int[] values = JsonConvert.DeserializeObject<int[]>(read);


// on Windows Phone 8
// input data
int[] value = { 2, 5, 7, 9, 42, 101 };

// persist data
string json = JsonConvert.SerializeObject(value);
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("myData.json", CreationCollisionOption.ReplaceExisting);
using (Stream current = await file.OpenStreamForWriteAsync())
{
    using (StreamWriter sw = new StreamWriter(current))
    {
        await sw.WriteAsync(json);
    }
}

// read back data
StorageFile file2 = await ApplicationData.Current.LocalFolder.GetFileAsync("myData.json");
string read;
using (Stream stream = await file2.OpenStreamForReadAsync())
{
    using (StreamReader streamReader = new StreamReader(stream))
    {
        read = streamReader.ReadToEnd();
    }
}
int[] values = JsonConvert.DeserializeObject<int[]>(read);

Upvotes: 3

Related Questions