Logan Stach
Logan Stach

Reputation: 23

Is there a way to save a list using Windows.Storage.ApplicationData with a foreach loop in a UWP app?

I am making a UWP app where I want to save the contents of a listbox when the user closes the application. I believe (although I may be wrong) that the best way to do this is by adding the contents of a listbox to a list . However, given the constraints of UWP, I can't use StreamWriter to save whatever variables I wish to save, which would allow me to do so easily. So, I am using StorageFolder.GetFileAsync.

While this is all well and good for saving a few variables, when the amount of variables I would like to save is not predetermined (i.e; a list) I'm not sure how to go about doing so.

private async void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            Windows.Storage.StorageFolder storageFolder = 
            Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile databaseFile = await 
            storageFolder.CreateFileAsync("database.txt", 
            Windows.Storage.CreationCollisionOption.ReplaceExisting);

            string databaseItem;
            string databaseName;
            double databaseFat;
            double databaseCarbs;
            double databaseProtein;
            string servingSize;

            txtNameDatabase.Text = txtCaloriesDatabase.Text = txtFatDatabase.Text = txtCarbsDatabase.Text = txtProteinDatabase.Text = txtServingSize.Text = "";
            int databaseCalories;

            ContentDialogResult databaseResult = await databaseContentDialog.ShowAsync();
            bool contentDialogError = false;

            if (databaseResult == ContentDialogResult.Primary)
            {
                try
                {
                    databaseName = txtNameDatabase.Text;
                    databaseCalories = Convert.ToInt32(txtCaloriesDatabase.Text);
                    databaseFat = Convert.ToDouble(txtFatDatabase.Text);
                    databaseCarbs = Convert.ToDouble(txtCarbsDatabase.Text);
                    databaseProtein = Convert.ToDouble(txtProteinDatabase.Text);
                    servingSize = txtServingSize.Text;


                    if (contentDialogError == false)
                    {

                        databaseItem = databaseName + ": " + databaseCalories + " Calories, " + databaseFat + "g Fat, " + databaseCarbs + "g Carbs, " + databaseProtein + "g Protein, Serving Size: " + databaseProtein;
                        foodDatabaseList.Add(databaseItem);
                        lstFoodDatabase.Items.Add(foodDatabaseList[0]);
                    }
                }
                catch
                {
                    var msgContentDialogError = new MessageDialog("Please only enter whole numbers into the calories field and decimal numbers into the macronutrient fields.");
                    await msgContentDialogError.ShowAsync();
                }
                foreach (string line in lstFoodDatabase.Items)
                {
                    await Windows.Storage.FileIO.WriteTextAsync(databaseFile, line);
                }
            }
        }

private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile databaseFile = await storageFolder.GetFileAsync("database.txt");

            string test = await Windows.Storage.FileIO.ReadTextAsync(databaseFile);
            lstFoodDatabase.Items.Add(test);

        }

I tried using a foreach loop to save each item in the listbox, but when I try to read it off, I only get the last item that was saved.

Upvotes: 0

Views: 171

Answers (1)

Anran Zhang
Anran Zhang

Reputation: 7737

When you want to save some structured data, there are usually two ways.
The first one is the database, but this method may not be suitable for your situation.
The second is to store the data as serializable text, such as JSON.

As you can see from your code, your foodDatabaseList is a List<string>, we will start here.

Before that, you need to install the Newtonsoft.Json nuget package.

StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile databaseFile = await storageFolder.CreateFileAsync("database.txt", CreationCollisionOption.ReplaceExisting);

// Data loading

// List serialization
string serialization = JsonConvert.SerializeObject(foodDatabaseList);
// Save them
await FileIO.WriteTextAsync(databaseFile, serialization);

If you need to read them

Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile databaseFile = await storageFolder.CreateFileAsync("database.txt", CreationCollisionOption.OpenIfExists);

string test = await FileIO.ReadTextAsync(databaseFile);

List<string> localItems = JsonConvert.DeserializeObject<List<string>>(test);

foreach (var item in localItems)
{
    lstFoodDatabase.Items.Add(item);
}

Best regards.

Upvotes: 1

Related Questions