.NET MAUI - Storing Data Locally Using SQLite and Preferences
Storing Data Locally Using SQLite and Preferences in .NET MAUI
In modern mobile applications, data storage is essential for providing offline capabilities, caching data, or saving user preferences. .NET MAUI offers several ways to store data locally, two of the most popular being SQLite and Preferences. In this blog, we'll dive deep into both approaches, explaining how they work, their use cases, and how to implement them in your .NET MAUI applications.
Join our exclusive WhatsApp group for Xamarin and .NET MAUI developers to connect with experts, share insights, and get help with your projects. Whether you're a beginner or an experienced developer, this group is the perfect place to enhance your skills and collaborate with the community.
Please, support my blog by clicking on our sponsors ad!
1. Storing Data with SQLite
SQLite is a lightweight, serverless, self-contained database engine that is commonly used in mobile applications. .NET MAUI supports SQLite through the SQLite-net-pcl
library, which allows you to store and query data locally in your app.
Step-by-Step Guide to Using SQLite in .NET MAUI
Step 1: Install SQLite NuGet Package
Before you start using SQLite, you need to install the SQLite-net-pcl
package to your .NET MAUI project. This can be done via the NuGet Package Manager or by using the following command in the terminal:
dotnet add package SQLite-net-pcl
Step 2: Create a Data Model
The first step in using SQLite is defining a model that will represent the data you want to store. This class will map to a table in the SQLite database. Here’s an example model:
using SQLite;
public class Person
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
- [PrimaryKey]: Marks the primary key of the table.
- [AutoIncrement]: Automatically increments the value for each new record.
- Properties: Each property corresponds to a column in the SQLite table.
Table of Contents for .Net Maui
- What is .NET MAUI and why it’s important
- Applying the MVVM pattern for cleaner architecture
- Working with Renderers and Mappers
- Storing data locally using SQLite and Preferences
- Image Picker from gallery
- Sending push notifications using Firebase
- Publishing your app to Android and iOS stores
- 🌟 Explore More Topics
Step 3: Set Up SQLite Database
You will need to create a SQLite connection that will allow you to interact with the database. It’s also a good idea to store the database file in the device's local storage.
using SQLite;
using System.IO;
public class DatabaseService
{
private SQLiteConnection _database;
public DatabaseService()
{
var databasePath = Path.Combine(FileSystem.AppDataDirectory, "people.db3");
_database = new SQLiteConnection(databasePath);
_database.CreateTable(); // Creates the table if it doesn't exist
}
// Add a new record
public void AddPerson(Person person)
{
_database.Insert(person);
}
// Retrieve all records
public List GetAllPeople()
{
return _database.Table().ToList();
}
}
- FileSystem.AppDataDirectory: This property ensures that the SQLite database is stored in the appropriate local storage directory depending on the platform (Android, iOS, etc.).
- SQLiteConnection: The connection to the SQLite database, allowing you to execute queries and interact with the database.
- CreateTablePerson
model if it doesn’t exist.
Step 4: Using SQLite in Your App
Now, you can use the DatabaseService
class to store and retrieve data:
public partial class MainPage : ContentPage
{
private readonly DatabaseService _databaseService;
public MainPage()
{
InitializeComponent();
_databaseService = new DatabaseService();
}
// Add a new person
private void AddPerson_Clicked(object sender, EventArgs e)
{
var person = new Person { Name = "John Doe", Age = 30 };
_databaseService.AddPerson(person);
}
// Get all people
private void GetAllPeople_Clicked(object sender, EventArgs e)
{
var people = _databaseService.GetAllPeople();
foreach (var person in people)
{
Console.WriteLine($"{person.Name}, {person.Age}");
}
}
}
2. Storing Data with Preferences
Preferences are a simple way to store key-value pairs locally on a device. .NET MAUI provides the Preferences
API to store small amounts of simple data, such as user settings, app configurations, or flags. Preferences are ideal for lightweight data storage and do not require the complexity of a full database like SQLite.
Step-by-Step Guide to Using Preferences in .NET MAUI
Step 1: Storing Data Using Preferences
To store a simple value in Preferences, you can use the Preferences.Set
method:
using Microsoft.Maui.Storage;
public void SavePreference(string key, string value)
{
Preferences.Set(key, value);
}
- Preferences.Set(key, value): Saves the value with the specified key.
Step 2: Retrieving Data from Preferences
To retrieve the stored data, you can use the Preferences.Get
method:
public string GetPreference(string key)
{
return Preferences.Get(key, string.Empty); // Default value is empty string
}
- Preferences.Get(key, defaultValue): Retrieves the value associated with the key, or the default value if the key doesn’t exist.
Step 3: Using Preferences in Your App
Here’s an example of using Preferences to store and retrieve a username in your application:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
// Save username
private void SaveUsername_Clicked(object sender, EventArgs e)
{
string username = "JohnDoe";
Preferences.Set("Username", username);
}
// Get username
private void GetUsername_Clicked(object sender, EventArgs e)
{
string username = Preferences.Get("Username", "Guest");
Console.WriteLine($"Hello, {username}!");
}
}
When to Use SQLite vs Preferences
- SQLite is best suited for structured data, relationships, or complex queries, such as storing user profiles, orders, or any other entities with multiple properties.
- Preferences is ideal for small, simple key-value data, such as storing user settings, flags, or simple user preferences.
Interview Questions
- What is SQLite, and why is it used in mobile applications?
- How does .NET MAUI handle local storage with SQLite and Preferences?
- What is the difference between SQLite and Preferences in .NET MAUI?
- Explain how to create a table in SQLite in .NET MAUI.
- What is the role of the
SQLite-net-pcl
library in working with SQLite in .NET MAUI? - Can Preferences be used for storing complex data types? Why or why not?
- What are the advantages of using SQLite over Preferences for data storage in a .NET MAUI app?
- What is the
FileSystem.AppDataDirectory
property used for in SQLite? - How would you handle database migrations when the schema changes in SQLite?
- When would you choose Preferences over SQLite, and why?
Conclusion
Storing data locally in a .NET MAUI app is a powerful feature that can greatly improve the user experience. Whether you're using SQLite for structured data or Preferences for simpler key-value storage, .NET MAUI provides flexible tools for both scenarios. Understanding these concepts will make your applications more efficient and user-friendly, while also preparing you for real-world development challenges and interviews.
Comments
Post a Comment