Shared Preferences In Xamarin Android

Introduction

In most cases, an application has a login screen for authenticating apps or accessing an application for further processing i.e. accessing data. There is another optionas well;  i.e., Remember Me on the login screen of the applicaition itself.

If you checked the checkbox of Remember Me at the time of login, when user opens an Application next time, then it directly navigates into app’s main screen, which is default screen after login without navigating to login screen.

Where we can use Shared Preference (Use Case)

  • When we want to achieve Remember Me functionality in our Application in Xamarin Android app, then we can use this feature by using Shared Preference.
  • Suppose, as a use case, if the user wants to use SQLite only for login because an app has crashed but the user wants to go to the same page where an app crashed. Then instead of using SQLite for this, you can use Shared Preference also in this scenario.

How to achieve this?

Let’s understand it step by step.

Solution

  1. Create a new project, choose Android => Blank App(Android), as shown in the screenshot given below and give it some meaningful name.

    Xamarin
  1. Create SplashScreenAcitvity.cs class, as shown below.

    Xamarin
  1. Set MainLauncher=true and Theme for cs as well, as shown in the screenshot given below.

    Xamarin

  2. The code for SplashScreenActivity.cs is given below.
    1. using Android.App;  
    2. using Android.Content;  
    3. using Android.OS;  
    4. using Newtonsoft.Json;  
    5. using System;  
    6.   
    7. namespace SharedPreferencesDemo  
    8. {  
    9.     [Activity(Theme = "@style/MyTheme.Splash", MainLauncher = true)]  
    10.     public class SplashScreenActivity : Activity  
    11.     {  
    12.         protected override void OnCreate(Bundle savedInstanceState)  
    13.         {  
    14.             base.OnCreate(savedInstanceState);  
    15.                           
    16. ISharedPreferences pref = Application.Context.GetSharedPreferences("UserInfo", FileCreationMode.Private);  
    17. string userName = pref.GetString("Username", String.Empty);  
    18. string password = pref.GetString("Password", String.Empty);  
    19.   
    20.             if (userName == String.Empty || password == String.Empty)  
    21.             {  
    22.                 //No saved credentials, take user to login screen  
    23.                 Intent intent = new Intent(thistypeof(MainActivity));  
    24.                 this.StartActivity(intent);  
    25.             }  
    26.   
    27.             else  
    28.             {  
    29.                 //There are saved credentials  
    30.   
    31.                 if (userName == "amit" && password == "amit")  
    32.                 {  
    33.                     //Successful take the user to application  
    34.                     Intent intent = new Intent(thistypeof(LoginSuccessActivity));  
    35.   
    36.                     User user = new User()  
    37.                     {  
    38.                         UserID = 1,  
    39.                         UserName = "amit",  
    40.                         Password = "amit"  
    41.                     };  
    42.   
    43. intent.PutExtra("User", JsonConvert.SerializeObject(user));  
    44.   
    45.                     this.StartActivity(intent);  
    46.                 }  
    47.   
    48.                 else  
    49.                 {  
    50.                     //Unsuccesful, take user to login screen  
    51.                     Intent intent = new Intent(thistypeof(MainActivity));  
    52.                     this.StartActivity(intent);  
    53.                     this.Finish();  
    54.                 }  
    55.             }  
    56.         }  
    57.         }  
    58. }  
  1. Go to reference by using NuGet Package Manager and download v7.AppCompat package in your project, as shown below.

    Xamarin
  1. Go to reference by using NuGet Package Manager and download Newtonsoft.json package in your project, as shown below.

    Xamarin
  1. Add Styles.xml in Resources=>values folder. The code is shown below.
    1. <?xml version="1.0" encoding="utf-8" ?>  
    2. <resources>  
    3.   <style name="MyTheme.Base" parent="Theme.AppCompat.Light">  
    4.   </style>  
    5.   
    6.   <style name="MyTheme" parent="MyTheme.Base">  
    7.   </style>  
    8.   
    9.   <style name="MyTheme.Splash" parent ="Theme.AppCompat.Light.NoActionBar">  
    10.     <item name="android:windowBackground">@drawable/splash_screen</item>  
    11.     <item name="android:windowNoTitle">true</item>  
    12.     <item name="android:windowFullscreen">true</item>  
    13.     <item name="android:windowContentOverlay">@null</item>  
    14.     <item name="android:windowActionBar">true</item>  
    15.   </style>  
    16. </resources>  
  1. Add splash_screen.xml in Resources=>drawable folder. The code is given below,
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <layer-list xmlns:android="http://schemas.android.com/apk/res/android">  
    3.   <item>  
    4.     <color android:color="@color/splash_background"/>  
    5.   </item>  
    6.   <item>  
    7.     <bitmap  
    8.         android:src="@drawable/logo"  
    9.         android:tileMode="disabled"  
    10.         android:gravity="center"/>  
    11.   </item>  
    12. </layer-list>  
  1. Slash screen looks, as shown below, when we run the Application.

    Xamarin
  1. After splash screen, we automatically navigate to MainActivity.cs. In MainActivity.cs is the default activity at the time of project creation but now SplashScreenActivity.cs is our starting activity. Hence, MainLauncher is not assigned in MainActivity.cs. The code for MainActivity.cs is given below.
    1. using Android.App;  
    2. using Android.Widget;  
    3. using Android.OS;  
    4. using Android.Content;  
    5. using Newtonsoft.Json;  
    6.   
    7. namespace SharedPreferencesDemo  
    8. {  
    9.     [Activity(Label = "Shared Preferences")]  
    10.     public class MainActivity : Activity  
    11.     {  
    12.         Button btnLogin;  
    13.         EditText userName, password;  
    14.         CheckBox mCbxRemMe;  
    15.         protected override void OnCreate(Bundle bundle)  
    16.         {  
    17.             base.OnCreate(bundle);  
    18.   
    19.             // Set our view from the "main" layout resource  
    20.              SetContentView (Resource.Layout.Main);  
    21.             userName = FindViewById<EditText>(Resource.Id.userNameEditText);  
    22. password = FindViewById<EditText>(Resource.Id.passwordEditText);  
    23.             btnLogin = FindViewById<Button>(Resource.Id.btnLogin);  
    24.             mCbxRemMe = FindViewById<CheckBox>(Resource.Id.cbxRememberMe);  
    25.   
    26.             btnLogin.Click += BtnLogin_Click;  
    27.         }  
    28.   
    29.         private void BtnLogin_Click(object sender, System.EventArgs e)  
    30.         {  
    31. Intent intent = new Intent(thistypeof(LoginSuccessActivity));  
    32.   
    33.             User user = new User()  
    34.             {  
    35.                 UserID = 1,  
    36.                 UserName = userName.Text,  
    37.                 Password = "amit"  
    38.             };  
    39.   
    40. intent.PutExtra("User", JsonConvert.SerializeObject(user));  
    41.   
    42.             if (mCbxRemMe.Checked)  
    43.             {  
    44. ISharedPreferences pref = Application.Context.GetSharedPreferences("UserInfo", FileCreationMode.Private);  
    45.                 ISharedPreferencesEditor edit = pref.Edit();  
    46.                 edit.PutString("Username", userName.Text.Trim());  
    47.                 edit.PutString("Password", password.Text.Trim());  
    48.                 edit.Apply();  
    49.             }  
    50.   
    51.             this.StartActivity(intent);  
    52.               
    53.             }  
    54.         }  
    55. }  
  1. Set Main.axml page to MainActivity.cs, as shown below.

    Xamarin
  2. Create design for Main.axml page and the code is given below.
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     android:layout_width="match_parent"  
    4.     android:layout_height="match_parent"  
    5.     android:gravity="center_horizontal"  
    6.     android:background="@android:color/holo_purple">  
    7.     <TextView  
    8.         android:layout_width="wrap_content"  
    9.         android:layout_height="wrap_content"  
    10.         android:text="Login"  
    11.         android:gravity="top"  
    12.         android:textSize="30dp"  
    13.         android:id="@+id/loginTitleText"  
    14.         android:layout_marginTop="50dp"  
    15.         android:layout_marginLeft="100dp" />  
    16.     <LinearLayout  
    17.         android:layout_width="wrap_content"  
    18.         android:layout_height="wrap_content"  
    19.         android:orientation="vertical"  
    20.         android:gravity="center"  
    21.         android:layout_gravity="center_vertical"  
    22.         android:background="@android:color/holo_purple"  
    23.         android:layout_below="@id/loginTitleText"  
    24.         android:layout_marginTop="30dp">  
    25.         <LinearLayout  
    26.             android:layout_width="match_parent"  
    27.             android:layout_height="wrap_content"  
    28.             android:orientation="horizontal"  
    29.             android:id="@+id/usernameLinearLayout">  
    30.             <EditText  
    31.                 android:layout_width="300dp"  
    32.                 android:layout_height="wrap_content"  
    33.                 android:id="@+id/userNameEditText"  
    34.                 android:layout_marginLeft="10dp"  
    35.                 android:hint="User Name"  
    36.                 android:backgroundTint="#fffaebd7" />  
    37.         </LinearLayout>  
    38.         <LinearLayout  
    39.             android:layout_width="match_parent"  
    40.             android:layout_height="wrap_content"  
    41.             android:orientation="horizontal"  
    42.             android:id="@+id/passwordLinearLayout">  
    43.             <EditText  
    44.                 android:layout_width="300dp"  
    45.                 android:layout_height="wrap_content"  
    46.                 android:id="@+id/passwordEditText"  
    47.                 android:password="true"  
    48.                 android:gravity="top"  
    49.                 android:layout_marginLeft="10dp"  
    50.                 android:hint="Password"  
    51.                 android:backgroundTint="#fffaebd7" />  
    52.         </LinearLayout>  
    53.         <Button  
    54.             android:layout_width="match_parent"  
    55.             android:layout_height="wrap_content"  
    56.             android:text="Login"  
    57.             android:background="@android:color/holo_blue_dark"  
    58.             android:layout_marginTop="20dp"  
    59.             android:backgroundTint="#ff4682b4"  
    60.             android:id="@+id/btnLogin"/>  
    61.         <CheckBox  
    62.             android:text="Remember Me"  
    63.             android:layout_width="match_parent"  
    64.             android:layout_height="wrap_content"  
    65.             android:id="@+id/cbxRememberMe"  
    66.             android:layout_marginTop="15dp"  
    67.             android:textStyle="bold"  
    68.             android:textColor="@android:color/white"   
    69.             android:button="@drawable/checkbox_ischecked"/>  
    70.       
    71.     </LinearLayout>  
    72. </RelativeLayout>  
  1. Added checkbox_ischecked.xml.

    Xamarin
  1. The code for ischecked.xml is given below.
    1. <?xml version="1.0" encoding="utf-8" ?>  
    2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
    3.   
    4.   <item android:state_checked="true"  
    5.         android:drawable="@android:drawable/checkbox_on_background"/>  
    6.   
    7.   <item android:state_checked="false"  
    8.                 android:drawable="@android:drawable/checkbox_off_background"/>  
    9. </selector>  
  1. The design, which  looks like Main.axml is given below.

    Xamarin
  1. Create LoginSuccessActivity.cs is given below.

    Xamarin
  1. Create LoginSuccess.axml page and the code for this page is given below.

    Xamarin
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     android:layout_width="match_parent"  
    4.     android:layout_height="match_parent">  
    5.     <TextView  
    6.         android:layout_width="wrap_content"  
    7.         android:layout_height="wrap_content"  
    8.         android:text="Login Successful"  
    9.         android:gravity="center"  
    10.         android:layout_gravity="fill_vertical"  
    11.         android:layout_centerInParent="true"  
    12.         android:textSize="20dp"  
    13.         android:textStyle="bold" />  
    14. </RelativeLayout>  
  1. Create User.cs class, which is used to store the details of the users and the code is given below.

    Xamarin
    1. Using system;  
    2. namespace SharedPreferencesDemo  
    3. {  
    4.     class User  
    5.     {  
    6.         public int UserID { get; set; }  
    7.         public string UserName { get; set; }  
    8.         public string Password { get; set; }  
    9.     }  
    10. }  

Output Windows for Shared Preferences demo project is given below.

  • Splash screen

    Xamarin

  • Login screen for username is virendra and password is virendra but won’t check the checkbox.

    Xamarin
  • After clicking Login button, it navigates to the Login Successful screen.

    Xamarin
  • When you run the app a second time, it will be, as shown below.
    Xamarin
  • Enter username as virendra and password as virendra.

    Xamarin
  • After clicking Login button, it successfully navigates to Login Successful screen.

    Xamarin
  • When the app is run a third time, the splash screen is given below.

    Xamarin
  • Enter username as amit and password as amit as well 

    Xamarin

  • After clicking on Login button, it successfully navigates to Login Successful screen.

    Xamarin
  • If you run the application a fourth time, the slash screen looks, as shown below.

    Xamarin
  • Enter username as amit and password as amit.

    Xamarin
  • After clicking on Login button, it successfully navigates to Login Successful screen.

    Xamarin
  • IF you run the Application a fifth time, it shows a splash screen, as shown below.

    Xamarin
  • Now, our Application directly navigates to loginSuccess screen from splash screen because of Shared Preference as record found username as amit and password as amit.

    Xamarin

Summary

We learned how to use Shared Preferences and its usage in Xamarin Android as well.


Similar Articles