简体   繁体   中英

How to save and load an observablecollection on app suspend and start?

I'm trying to figure out how to save observablecollection items when the app is closed or suspended, and then reload them when the app is opened again. This is what I have, but because the methods are static, and are being called from the App.xaml.cs file, the MemoryItems observablecollection requires a reference. So, I don't really understand how to save and update the observablecollection. I tried to use an instance of the ViewModel in the App.xaml.cs file, but then I get zero items in MemoryItems observablecollection.

public ObservableCollection<MemoryItem> MemoryItems { get; set; } = new ObservableCollection<MemoryItem>();

public MainPageViewModel()
{           
}

public string MemoryValue
{
   get
   {
       return _memoryValue;
   }
   set
   {
       _memoryValue = value;
       OnPropertyChanged("MemoryValue");
   }
}


public static async Task Serializer()
{
    var folder = ApplicationData.Current.RoamingFolder;
    var file = await folder.CreateFileAsync("collection.json", CreationCollisionOption.ReplaceExisting);
    using (var stream = await file.OpenStreamForWriteAsync())
    using (var writer = new StreamWriter(stream, Encoding.UTF8))
    {
        string json = JsonConvert.SerializeObject(MemoryItems);                
        await writer.WriteAsync(json);
    }
}

public static async Task Deserializer()
{
    try
    {
        var folder = ApplicationData.Current.RoamingFolder;
        var file = await folder.GetFileAsync("collection.json");
        using (var stream = await file.OpenStreamForReadAsync())
        using (var reader = new StreamReader(stream, Encoding.UTF8))
        {
            string json = await reader.ReadToEndAsync();                    
            MemoryItems = JsonConvert.DeserializeObject<ObservableCollection<MemoryItem>>(json);
        }               
    }
    catch (Exception)
    {
        // Handle Exception.
    }
}

Then in the App.xaml.cs file

public async void OnSuspending(object sender, SuspendingEventArgs args)
{
    SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();

    await MainPageViewModel.Serializer();

    deferral.Complete();
 }

public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
    NavigationService.Navigate(typeof(Views.MainPage));

    await MainPageViewModel.Deserializer();

    await Task.CompletedTask;

 }

My solution was to remove the static keywords and handle everything in the viewmodel using the To and From OnNavigatedAsync methods. I don't anticipate a lot of data being restored each time the application starts, and this is working, so as inelegant as it may be, it gets the job done.

        private bool newPage = true;

        public override async Task OnNavigatedFromAsync(IDictionary<string, object> suspensionState, bool suspending)
    {
        await Serializer();
    }

    public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
    {
        if (newPage == true) 
        {
            await Deserializer();
            newPage = false;
        }
    }


public async Task Serializer()
    {
        var folder = ApplicationData.Current.RoamingFolder;
        var file = await folder.CreateFileAsync("collection.json", CreationCollisionOption.ReplaceExisting);
        using (var stream = await file.OpenStreamForWriteAsync())
        using (var writer = new StreamWriter(stream, Encoding.UTF8))
        {
            string json = JsonConvert.SerializeObject(MemoryItems);
            await writer.WriteAsync(json);
        }
    }
    public async Task Deserializer()
    {
        try
        {
            var folder = ApplicationData.Current.RoamingFolder;
            var file = await folder.GetFileAsync("collection.json");
            using (var stream = await file.OpenStreamForReadAsync())
            using (var reader = new StreamReader(stream, Encoding.UTF8))
            {
                var json = await reader.ReadToEndAsync();
                ObservableCollection<MemoryItem> MemoryItems = JsonConvert.DeserializeObject<ObservableCollection<MemoryItem>>(json);

                if(MemoryItems.Count != 0)
                {
                    foreach (var item in MemoryItems)
                    {
                        var sb = new StringBuilder();
                        sb.Append(item.Memory);
                        var fileString = sb.ToString();

                        var memoryItem = new MemoryItem
                        {
                            Memory = fileString
                        };
                        this.MemoryItems.Add(memoryItem);
                    }
                }
                else
                {
                    Memory();
                } 
            }
        }
        catch (Exception)
        {
            // Handle Exception.
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM