Google AppSettings: How to store user settings in Xamarin.Forms? (C# - Xaml) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Sunday, 1 April 2018

AppSettings: How to store user settings in Xamarin.Forms? (C# - Xaml)

Introduction:
Settings plugin makes it easier to create cross-platform .NET apps and have cross platform settings. Manage and use all settings from one PCL/NetStandard library and save natively on each platform. Also this plugin stores settings natively on each platform and does NOT save them to Json. This allows you to use native functionality such as SharedPreferences on Android and NSUserDefaults on iOS.

Requirements:
  • This article source code is prepared by using Visual Studio Community for Mac (7.4). And it is better to install latest visual studio updates from here.
  • This sample project is Xamarin.Forms PCL project and tested in Android emulator and iOS simulators.
  • Used Settings Nuget Package version is V3.1.1.
Description:
This article can explain you below topics:
1. How to create Xamarin.Forms PCL project with Visual Studio for Mac?
2. How to store and read string values using Settings? 
3. How to implement login/logout pages functionality using Settings?
1. How to create Xamarin.Forms PCL project with Visual studio for Mac?
First we need to create the new Xamarin.Forms project. 
  • Launch Visual Studio for Mac.
  • On the File menu, select New Solution.
  • The New Project dialog appears. In the left pane Multiplatform App Xamarin.Forms > Blank Forms App and click on Next.
  • Enter your App Name (Ex: AppSettingsSample). Select Target Platforms to Android & iOS and Shared Code to Portable Class Library  after that click on Next button.


  • You can choose your project location like below and Create new project.

And project structure will be.
  • AppSettingsSample: It is for PCL shared code.
  • AppSettingsSample.Droid: It is for Android.
  • AppSettingsSample.iOS: It is for iOS.
2. How to store and read string values using Settings?
We need to follow below few steps to store user settings in Xamarin.Forms.
Step 1: Add Settings Nuget Package:
Right click on Packages folder => Add Packages.
After that Add Packages window will open, search for "Xam.Plugins.Settings" and click on Add Package to install it.


Now your PCL project should include above package like below:
Also please add above package to AppSettingsSample.Droid and AppSettingsSample.iOS projects by following same above steps like AppSettingsSample PCL project. And make sure same version Settings package should add to Android and iOS project Packages folder like below.
Step 2: Create a Helper Class that properties need to store:
Create Helpers folder in PCL, after that right click on Models folder => Add =>New File => General => Empty Class and name it UserSettings.
UserSettings.cs
Open UnserSettings class file and add below properties:
  1. // Helpers/Settings.cs  
  2. using Plugin.Settings;  
  3. using Plugin.Settings.Abstractions;  
  4.   
  5. namespace AppSettingsSample.Helpers  
  6. {  
  7.     /// <summary>  
  8.     /// This is the Settings static class that can be used in your Core solution or in any  
  9.     /// of your client applications. All settings are laid out the same exact way with getters  
  10.     /// and setters.   
  11.     /// </summary>  
  12.     public static class UserSettings  
  13.     {  
  14.         static ISettings AppSettings {  
  15.             get {  
  16.                 return CrossSettings.Current;  
  17.             }  
  18.         }  
  19.   
  20.         public static string UserName  
  21.         {  
  22.             get => AppSettings.GetValueOrDefault(nameof(UserName), string.Empty);  
  23.             set => AppSettings.AddOrUpdateValue(nameof(UserName), value);  
  24.         }  
  25.   
  26.         public static string Password  
  27.         {  
  28.             get => AppSettings.GetValueOrDefault(nameof(Password), string.Empty);  
  29.             set => AppSettings.AddOrUpdateValue(nameof(Password), value);  
  30.         }  
  31.   
  32.         public static string MobileNumber  
  33.         {  
  34.             get => AppSettings.GetValueOrDefault(nameof(MobileNumber), string.Empty);  
  35.             set => AppSettings.AddOrUpdateValue(nameof(MobileNumber), value);  
  36.         }  
  37.   
  38.         public static void ClearAllData()  
  39.         {  
  40.             AppSettings.Clear();  
  41.         }  
  42.   
  43.     }  
  44. }  
Above helper class will helpful to store/read string values(UserName, Password, MobileNumber). Also we added method to clear all user settings values.
This library uses the native settings management, which means all settings are persisted across app updates, saved natively, and can be integrated into native settings. 
  • Android: SharedPreferences 
  • Apple: NSUserDefaults 
  • UWP: ApplicationDataContainer .
  • NET: UserStore -> IsolcatedStorageFile
Note:
Since data is stored natively on each platform only certain data types are supported by Settings plugin: 
  • Boolean 
  • Int32 
  • Int64 
  • String 
  • Single(float) 
  • Double 
  • Decimal 
  • DateTime (Stored and retrieved in UTC).

3. How to implement login/logout pages functionality using Settings?
Now we can create a sample for below login/logout functionality.
  • After login success, app should not show the login page until logout from the app.
  • If user logout from the application, app need to redirect to login page.

ViewModels:
It is best practices to write business logic in view models before start to build views user interface. Create ViewModels folder in PCL and add functionality for the view models below.
BasePageViewModel.cs
This view model will helpful to store/read string values(UserName, Password, MobileNumber).
  1. using System.ComponentModel;  
  2. using System.Runtime.CompilerServices;  
  3. using AppSettingsSample.Helpers;  
  4. using Xamarin.Forms;  
  5.   
  6. namespace AppSettingsSample.ViewModels  
  7. {  
  8.     public class BasePageViewModel : INotifyPropertyChanged {  
  9.   
  10.         public INavigation _navigation;  
  11.         public string UserName    
  12.         {    
  13.             get => UserSettings.UserName;   
  14.             set{  
  15.                 UserSettings.UserName = value;  
  16.                 NotifyPropertyChanged("UserName");  
  17.             }  
  18.         }       
  19.   
  20.         public string Password    
  21.         {  
  22.             get => UserSettings.Password;   
  23.             set {   
  24.                 UserSettings.Password = value;   
  25.                 NotifyPropertyChanged("Password");  
  26.             }  
  27.         }    
  28.   
  29.         public string MobileNumber    
  30.         {  
  31.             get => UserSettings.MobileNumber;   
  32.             set {   
  33.                 UserSettings.MobileNumber = value;   
  34.                 NotifyPropertyChanged("MobileNumber");  
  35.             }  
  36.         }   
  37.  
  38.         #region INotifyPropertyChanged      
  39.         public event PropertyChangedEventHandler PropertyChanged;  
  40.         protected void NotifyPropertyChanged([CallerMemberName] string propertyName = ""){  
  41.             PropertyChanged?.Invoke(thisnew PropertyChangedEventArgs(propertyName));  
  42.         }  
  43.         #endregion  
  44.     }  
  45. }  
LoginPageViewModel.cs
This view model will helpful to store string values (UserName, Password, MobileNumber) also for user login.
  1. using System.Threading.Tasks;  
  2. using System.Windows.Input;  
  3. using AppSettingsSample.Views;  
  4. using Xamarin.Forms;  
  5.   
  6. namespace AppSettingsSample.ViewModels  
  7. {  
  8.     public class LoginPageViewModel : BasePageViewModel {  
  9.   
  10.         public ICommand LoginCommand { getprivate set; }  
  11.   
  12.         public LoginPageViewModel(INavigation navigation){  
  13.             _navigation = navigation;  
  14.   
  15.             LoginCommand = new Command(() =>  UpdateUserInfo());   
  16.         }  
  17.   
  18.         void UpdateUserInfo() {  
  19.             _navigation.PushAsync(new HomePage());  
  20.         }  
  21.     }  
  22. }  
HomePageViewModel.cs
This view model will helpful to read string values (UserName, Password, MobileNumber) also for user logout.
  1. using System.Threading.Tasks;  
  2. using System.Windows.Input;  
  3. using AppSettingsSample.Helpers;  
  4. using AppSettingsSample.Views;  
  5. using Xamarin.Forms;  
  6.   
  7. namespace AppSettingsSample.ViewModels  
  8. {  
  9.     public class HomePageViewModel: BasePageViewModel {  
  10.         public ICommand LogoutCommand { getprivate set; }  
  11.         public HomePageViewModel(INavigation navigation) {  
  12.             _navigation = navigation;  
  13.             LogoutCommand = new Command(() =>  ResetUserInfo());   
  14.         }  
  15.   
  16.         void ResetUserInfo()  
  17.         {  
  18.             _navigation.PushAsync(new LoginPage());  
  19.             UserSettings.ClearAllData();  
  20.         }  
  21.     }  
  22. }  

Views:
Create Views folder in PCL and add below xaml content pages.
LoginPage.xaml
This page is for User Login UI.
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"   
  3.               BackgroundColor="#D5E7FA" x:Class="AppSettingsSample.Views.LoginPage">    
  4.    <StackLayout Spacing="20" Margin="10" VerticalOptions="Center">      
  5.             <Entry Placeholder="User Name" Text="{Binding UserName}" HeightRequest="40" HorizontalOptions="FillAndExpand"  TextColor="Gray" BackgroundColor="White"/>      
  6.             <Entry Placeholder="Password" Text="{Binding Password}" IsPassword="true" HeightRequest="40" HorizontalOptions="FillAndExpand"  TextColor="Gray" BackgroundColor="White"/>  
  7.             <Entry Placeholder="Mobile Number" Keyboard="Telephone" Text="{Binding MobileNumber}" HeightRequest="40" HorizontalOptions="FillAndExpand"  TextColor="Gray" BackgroundColor="White"/>          
  8.             <Button Text="Login" HorizontalOptions="FillAndExpand" TextColor="Blue" Command="{Binding LoginCommand}" HeightRequest="40"  BackgroundColor="White"/>      
  9.             </StackLayout>    
  10. </ContentPage>    
LoginPage.xaml.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using AppSettingsSample.ViewModels;  
  4. using Xamarin.Forms;  
  5.   
  6. namespace AppSettingsSample.Views  
  7. {  
  8.     public partial class LoginPage : ContentPage  
  9.     {  
  10.         public LoginPage()  
  11.         {  
  12.             InitializeComponent();  
  13.             BindingContext = new LoginPageViewModel(Navigation);  
  14.         }  
  15.     }  
  16. }  
HomePage.xaml
This page is for User Logout UI.

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"   
  3.               BackgroundColor="#D5E7FA" x:Class="AppSettingsSample.Views.HomePage">  
  4.    <StackLayout Padding="40,60,40,0" Spacing="30">      
  5.             <Label Text="User Details" TextColor="Blue" HorizontalOptions="CenterAndExpand" FontSize="30"/>      
  6.             <StackLayout Spacing="10">   
  7.             <Label Text="UserName:" Font="20" TextColor="Black" HorizontalOptions="FillAndExpand"/>  
  8.             <Label Text="{Binding UserName}" HorizontalOptions="FillAndExpand" TextColor="Gray"/>   
  9.             <Label Text="Mobile Number:" Font="20" HorizontalOptions="FillAndExpand" TextColor="Black"/>  
  10.             <Label Text="{Binding MobileNumber}" HorizontalOptions="FillAndExpand" TextColor="Gray"/>    
  11.             <Button Text="Logout" HorizontalOptions="FillAndExpand" TextColor="Blue" Command="{Binding LogoutCommand}" HeightRequest="40"  BackgroundColor="White"/>      
  12.             </StackLayout>      
  13.      </StackLayout>       
  14. </ContentPage>  
HomePage.xaml.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using AppSettingsSample.ViewModels;  
  4. using Xamarin.Forms;  
  5.   
  6. namespace AppSettingsSample.Views  
  7. {  
  8.     public partial class HomePage : ContentPage  
  9.     {  
  10.         public HomePage()  
  11.         {  
  12.             InitializeComponent();  
  13.             BindingContext = new HomePageViewModel(Navigation);  
  14.         }  
  15.     }  
  16. }  

Demo screens from Android:

Demo screens from iOS:

You can also directly work on below sample source code to understand this article. 

AppSettingsSample

FeedBack Note: Please share your thoughts, what you think about this post, Is this post really helpful for you? I always welcome if you drop comments on this post and it would be impressive.

Follow me always at @Subramanyam_B
Have a nice day by  :)

No comments:

Post a Comment

Search Engine Submission - AddMe