Search code examples
c#xamarin.formsxamarin.androidstreamreader

How to fill out a form from StreamReader in Xamarin Forms


I am creating a project in Xamarin Forms that allows the user to type in their name, a username, a password, and use a stepper to tell their age and a switch to identify if the user is a student. The user can then hit save, and the information will be saved to a file via StreamWriter. The user will then be able to hit "Load" and all of their saved information will auto-populate the entry boxes, the age value, and the student "true or false" switch. I am having trouble in the MainPage.xaml.cs class with loading the saved information to populate the fields. I have binded the control names in the MainPage.xaml to the property values in my EntryFields class. This is my first time using Xamarin Forms and I am stuck. Please help :) Here's what I have for my saved method so far before I got stuck:

        {
            List<string> data = new List<string>();
            bool stepValue;
            int ageValue;
            //Read data from file
            if (File.Exists(_fileName))
            {
                using (var reader = new StreamReader(_fileName))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        data.Add(line);
                    }
                    
                    for(int i = 0; i < data.Count; i++)
                    {
                        if (data[4] == "true")
                        {
                            stepValue = true;
                        }
                        else if (data[4] == "false")
                        {
                            stepValue = false;
                        }
                        ageValue = Int32.Parse(data[3]);
                        //This is where I am stuck. I want to add each item to my list of EntryFields
                        //but I am not sure how since they're all different values.
                    }
                    

                }
            }
            else
            {
                DisplayAlert("Error", "Unable to load. Fill out required information and select SAVE.", "Go Back");
            }


        }

Here is my EntryFields class that looks like this:

    {
        public bool TrueOrFalse { get; set; }

        public string Name { get; set; }
        
        public string Username { get; set; }

        public string Password { get; set; }

        public int Age { get; set; }

        public EntryFields(string name, string username, string password, int age, string student)
        {
            Name = name;
            Username = username;
            Password = password;
            Age = age;
            if (student.ToLower() == "true")
            {
                TrueOrFalse = true;
            }
            else if(student.ToLower() == "false")
            {
                TrueOrFalse = false;
            }
        }
    }

Finally, so we are all looking at the same thing, here is my MainPage.xaml class:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MorganHall_CE01.MainPage">

    <StackLayout IsVisible="True">
        <Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
            <Label Text="Code Exercise 1" HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/>
        </Frame>
        <Entry x:Name="nameEntry" Placeholder="Enter Name Here" HorizontalOptions="FillAndExpand" HorizontalTextAlignment="Center" Text="{Binding Path=Name}" TextColor="#514E4E" />
        <Entry x:Name="usernameEntry" Placeholder="Enter Username Here" HorizontalOptions="FillAndExpand" HorizontalTextAlignment="Center" Text="{Binding Username}" TextColor="#514E4E" />
        <Entry x:Name="passwordEntry" Placeholder="Enter Password Here" HorizontalOptions="FillAndExpand" HorizontalTextAlignment="Center" Text="{Binding Password}" IsPassword="True" TextColor="#514E4E" />
        <StackLayout Orientation="Horizontal" Margin="10">
            <Label x:Name="ageLabel" Text="Age: " HorizontalTextAlignment="Start" HorizontalOptions="FillAndExpand" FontAttributes="Bold" TextColor="#000000" />
            <Stepper x:Name="ageStepper" Minimum="0" Maximum="100" Increment="1" Margin="50,0" Value="{Binding Age}" />
        </StackLayout>
        <StackLayout Orientation="Horizontal">
            <Label x:Name="studentLabel" Text="Enrolled Student: " HorizontalTextAlignment="Start" HorizontalOptions="FillAndExpand" FontAttributes="Bold" TextColor="#000000" />
            <Switch x:Name="studentSwitch" IsToggled="{Binding TrueOrFalse}" Margin="50,0" OnColor="#60E848" ThumbColor="#484453" />
        </StackLayout>
        <StackLayout Orientation="Horizontal">
            <Button x:Name="loadData" Text="Load" HorizontalOptions="EndAndExpand" FontAttributes="Bold" BackgroundColor="#138A83" TextColor="#FDFAFA" />
            <Button x:Name="saveData" Text="Save" HorizontalOptions="StartAndExpand" FontAttributes="Bold" BackgroundColor="#075D7F" TextColor="#FBF8F8" />
        </StackLayout>
    </StackLayout>
</ContentPage>

In the MainPage.xaml.cs class, I have a list of EntryFields that looks like this: private List<EntryFields> entries = new List<EntryFields>();

Please tell me there is a better and easier way to load the saved information. I am all confused. Thanks in advance! :)


Solution

  • something like this should work

    var entries = new EntryFields();
    
    // this will read all the file data into a string array
    var data = File.ReadAllLines(_fileName);
    
    // you will need to be sure the order matches the order you saved in
    entries.Name = data[1];
    entries.Username = data[2];
    entries.Password = data[3];
    entries.Age = int.Parse(data[4]);
    
    // set the binding context of the page
    this.BindingContext = entries;