Swift week Spring sales
Save up to 80 % on our Swift e-learning courses. Only this week!
Get up to 60 % extra points for free! More info

Lesson 5 - Saving and Loading Data in Xamarin Using Text Files

In the previous lesson of our cross-platform mobile applications development course, Styling and Debugging Xamarin Apps on Android Devices, we talked about debugging and styling using the Xamarin technology. Today, we're going to create a notepad application. We'll learn how to save and load data to/from a file and later from an SQLite database as well.

Form Layout

Let's create a new empty project of the Xamarin.forms type, which we'll name e.g. Notes. We'll update the installed packages before we start programming. To do this, we'll right-click the Notes project in Solution Explorer and select Manage NuGet packages. Next, we'll open the Installed tab, check all and select Update. We'll agree with the license terms, and now we can start programming.

Let's open the MainPage.xaml file and remove the following lines and the contents between the <stackLayout></stackLayout> tags from the <contentPage></contentPage> element:

xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"

We'll change the <StackLayout> to the following:

<StackLayout Margin="10,35,10,10">
        <Label Text="Notes"
               HorizontalOptions="Center"
               FontAttributes="Bold" />
        <Editor x:Name="editor"
                Placeholder="Write a note"
                HeightRequest="100" />
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
            <Button Text="Save"
                    Clicked="OnSaveButtonClicked" />
            <Button Grid.Column="1"
                    Text="Delete"
                    Clicked="OnDeleteButtonClicked"/>
        </Grid>
</StackLayout>

The XAML code is simple and should be clear to us after the previous lesson. In short, we created a Label with a bold, centered heading "Notes", a text editor with the height of 100 units and horizontal "Save" and "Delete" buttons. We'll save the file and move to MainPage.xaml.cs.

MainPage.xaml.cs

First, we can delete unnecessary using statements (the gray ones).

Into the class body (above the MainPage() constructor), we'll add a path to the file where our data will be saved or read from:

string _fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "notes.txt");

We'll add the necessary using system.IO by placing the cursor on the red-underline, clicking the dropdown next to the light bulb icon and choosing the relevant using directive.

Now, we'll check whether the file exists using a simple condition. If so, we'll read the saved text:

if (File.Exists(_fileName))
{
    editor.Text = File.ReadAllText(_fileName);
}

Now, we just need to create events for the buttons. Again, it's nothing complicated and everyone will understand the code for sure. If not, I recommend going back to the C# basics, as they aren't part of this tutorial.

void OnSaveButtonClicked(object sender, EventArgs e)
{
    File.WriteAllText(_fileName, editor.Text);
}

void OnDeleteButtonClicked(object sender, EventArgs e)
{
    if (File.Exists(_fileName))
    {
        File.Delete(_fileName);
    }
    editor.Text = string.Empty;
}

Just to be sure, the entire MainPage.xaml.cs code looks as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Notes
{
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        string _fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "notes.txt");

        public MainPage()
        {
            InitializeComponent();

            if (File.Exists(_fileName))
            {
                editor.Text = File.ReadAllText(_fileName);
            }
        }

        void OnSaveButtonClicked(object sender, EventArgs e)
        {
            File.WriteAllText(_fileName, editor.Text);
        }

        void OnDeleteButtonClicked(object sender, EventArgs e)
        {
            if (File.Exists(_fileName))
            {
                File.Delete(_fileName);
            }
            editor.Text = string.Empty;
        }
    }
}

All we have to do is connect the device or use the emulator to test the application. It should look something like this:

Notes in Xamarin and C# .NET

As we can see, the program isn't very useful yet. The note is saved to a file, so when we close the app, remove it from memory, and relaunch it, we'll see our note again. However, we probably want to save more than one note. Let's change the application's code and create screens to list all saved notes, save a new note, and edit an existing one.

Multi-Screen Application

As we've already said, we have to create 3 different screens (pages). These are:

  • listing the notes
  • creating a new note
  • editing an existing note

We're going to need a navigation to switch between the pages and hence some logic. So just one MainPage class isn't enough.

Preparing the Project

First, we'll add a new folder to the project, which we'll name Models/. Right-click on the project in Solution Explorer and select Add -> New Folder. In the Models/ folder, create a C# class (by right-clicking on the Models/ folder and selecting Add -> class). We'll name the class Note.cs.

Next, we add 2 pages of content - Notes.xaml and AddNote.xaml. To add them, right click on the project and select Add -> New Item -> Content Page.

That would be all for today's lesson. In the next lesson, Working with Text Files in Xamarin - Completing the Notepad, we'll complete the Xamarin notepad application with saving to a file and start working on a database-based version. If you have any problems and need to check your code, the whole project can be downloaded below.


 

 

Activities (2)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!