Persistent Storage In Xamarin Android App Using Shared Preferences

Introduction

Xamarin is a platform to develop cross-platform and multi-platform apps (like Windows phone, Android, iOS). In Xamarin, the code sharing concept is used. In Xamarin Studio, Visual Studio is also available.
 
Step 1

Create a new blank Android app, using Visual Studio.
 
Step 2

In your project solution, there is a Main.axml file. Now, open this file in designer view. Drag and drop one EditText, and two Buttons from toolbox. First button is used to write the user entered data into settings while the second button is used to show the data on layout 1 from Settings.
 
Write the code, mentioned below, into Main.axml.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">  
  6.     <EditText  
  7.         android:layout_width="match_parent"  
  8.         android:layout_height="wrap_content"  
  9.         android:id="@+id/editText1" />  
  10.     <Button  
  11.         android:text="Add"  
  12.         android:layout_width="match_parent"  
  13.         android:layout_height="wrap_content"  
  14.         android:id="@+id/btnAdd" />  
  15.     <Button  
  16.         android:text="Show Data on Layout 1"  
  17.         android:layout_width="match_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:id="@+id/btnShowData" />  
  20. </LinearLayout>  
Write the code, mentioned below, into MainActivity.cs.
  1. namespace MyApp  
  2. {  
  3.     [Activity(Label = "Persist a Value in Xamarin", MainLauncher = true, Icon = "@drawable/icon")]  
  4.     public class MainActivity : Activity  
  5.     {  
  6.         public static ISharedPreferences sharedPrefernce;  
  7.         Button mButton;  
  8.         EditText nameBox;  
  9.         protected override void OnCreate(Bundle bundle)  
  10.         {  
  11.             base.OnCreate(bundle);  
  12.             SetContentView(Resource.Layout.Main);  
  13.             Button button = FindViewById<Button>(Resource.Id.btnAdd);  
  14.             button.Click += delegate  
  15.             {  
  16.                 nameBox = FindViewById<EditText>(Resource.Id.editText1);  
  17.                 string name = nameBox.Text.ToString();                  
  18.                 Helper.UserSetting.Name = name;  
  19.                 // show a message pop up after clicking on Add button  
  20.                 Android.Widget.Toast.MakeText(this"Item Added Successfully", ToastLength.Short).Show();                  
  21.             };  
  22.             mButton = FindViewById<Button>(Resource.Id.btnShowData);  
  23.             mButton.Click += mButton_Click;  
  24.         void mButton_Click(object sender, EventArgs e)  
  25.         {  
  26.             Intent intent = new Intent(thistypeof(Layout1));  
  27.             this.StartActivity(intent);  
  28.         }  
  29.     }      
  30. }  
Step 3

Now, install the below NuGet package from NuGet Console Manager.

Install-Package Xam.Plugins.Settings -Version 2.5.1
 
Create one "Helper" folder in your project and add a new class i.e UserSetting.cs.
  • Create a new static class
    To create a new static class, call "Settings" in your shared code project or PCL that will house all of your settings.

  • Gain Access to ISettings
    When you want to read/write settings, you need to gain access via the ISettings API. This has a singleton setup.

  • Create Getters and Setters for your Setting
    We can access it from any project, whether it is a PCL, Shared Code, or a platform specific project. We do this by using these two methods in the ISettings API i.e GetValueOrDefault and AddOrUpdateValue.
Write the code, mentioned below, into UserSetting.cs.
  1. using Plugin.Settings;  
  2. using Plugin.Settings.Abstractions;  
  3.   
  4. namespace MyApp.Helper  
  5. {  
  6.    public static class UserSetting  
  7.     {  
  8.        private static ISettings AppSettings  
  9.        {  
  10.            get { return CrossSettings.Current; }  
  11.        }  
  12.         
  13.        public static string Name  
  14.        {  
  15.            get { return AppSettings.GetValueOrDefault<string>("Name"string.Empty); }  
  16.            set { AppSettings.AddOrUpdateValue<string>("Name", value); }  
  17.        }  
  18.     }  
  19. }  
Step 4

Now, create a layout to show the data on Layout 1. Write the code, mentioned below, into Layout1.axml.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">   
  6.     <TextView  
  7.         android:text=""  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:id="@+id/resultTxt" />      
  11.     <Button  
  12.         android:text="View Layout 2"  
  13.         android:layout_width="match_parent"  
  14.         android:layout_height="wrap_content"  
  15.         android:id="@+id/btnViewLayout2" />  
  16. </LinearLayout>  
Create class for Layout 1 and write the code, mentioned below, into Layout1.cs.
  1. namespace MyApp  
  2. {  
  3.    [Activity(Label = "Layout 1")]  
  4.    public  class Layout1 : Activity  
  5.     {  
  6.        Button btnView2;    
  7.        protected override void OnCreate(Bundle savedInstanceState)  
  8.        {  
  9.            base.OnCreate(savedInstanceState);  
  10.            SetContentView(Resource.Layout.Layout1);  
  11.            var viewLayout1 = FindViewById<TextView>(Resource.Id.resultTxt);    
  12.            var result =  Helper.UserSetting.Name;  
  13.            viewLayout1.Text = result.ToString();  
  14.            btnView2 = FindViewById<Button>(Resource.Id.btnViewLayout2);  
  15.            btnView2.Click += btnView2_Click;  
  16.        }  
  17.        private void btnView2_Click(object sender, EventArgs e)  
  18.        {  
  19.            Intent intent = new Intent(this, typeof(Layout1));  
  20.            this.StartActivity(intent);  
  21.        }  
  22.     }   
  23. }  
Step 5

Now, create a layout to show the data on Layout 2. Write the code, mentioned below, to Layout2.axml.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">  
  6.   <TextView  
  7.       android:text=""  
  8.       android:layout_width="match_parent"  
  9.       android:layout_height="wrap_content"  
  10.       android:id="@+id/resultTxt" />  
  11. </LinearLayout>  
Create class for Layout 2 and write the code, mentioned below, to Layout2.cs.
  1. namespace MyApp  
  2. {  
  3.     [Activity(Label = "Layout 2")]  
  4.     public class layout2 : Activity  
  5.     {  
  6.         protected override void OnCreate(Bundle savedInstanceState)  
  7.         {  
  8.             base.OnCreate(savedInstanceState);  
  9.             SetContentView(Resource.Layout.Layout2);  
  10.             var viewLayout2 = FindViewById<TextView>(Resource.Id.resultTxt);  
  11.             var result = Helper.UserSetting.Name;  
  12.             viewLayout2.Text = result.ToString();  
  13.         }  
  14.     }  
  15. }  
Step 6

Now, run the application on emulator.


Enter some text and click on Add button. You will see the screen like the following screenshot, along with a popup message.

 
 
 Now, click on "Show Data on Layout 1" button. You will see the below output.

 
 
Now, click on the "View Layout 2" button. Here is the output. 

 
 
Summary

This article will help the fresher candidates on how to consume persistent storage In Xamarin Android app, using Shared Preferences.

Up Next
    Ebook Download
    View all
    Learn
    View all