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)

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. namespace SharedPreferencesDemo
    7. {
    8. [Activity(Theme = "@style/MyTheme.Splash", MainLauncher = true)]
    9. public class SplashScreenActivity : Activity
    10. {
    11. protected override void OnCreate(Bundle savedInstanceState)
    12. {
    13. base.OnCreate(savedInstanceState);
    14. ISharedPreferences pref = Application.Context.GetSharedPreferences("UserInfo", FileCreationMode.Private);
    15. string userName = pref.GetString("Username", String.Empty);
    16. string password = pref.GetString("Password", String.Empty);
    17. if (userName == String.Empty || password == String.Empty)
    18. {
    19. //No saved credentials, take user to login screen
    20. Intent intent = new Intent(this, typeof(MainActivity));
    21. this.StartActivity(intent);
    22. }
    23. else
    24. {
    25. //There are saved credentials
    26. if (userName == "amit" && password == "amit")
    27. {
    28. //Successful take the user to application
    29. Intent intent = new Intent(this, typeof(LoginSuccessActivity));
    30. User user = new User()
    31. {
    32. UserID = 1,
    33. UserName = "amit",
    34. Password = "amit"
    35. };
    36. intent.PutExtra("User", JsonConvert.SerializeObject(user));
    37. this.StartActivity(intent);
    38. }
    39. else
    40. {
    41. //Unsuccesful, take user to login screen
    42. Intent intent = new Intent(this, typeof(MainActivity));
    43. this.StartActivity(intent);
    44. this.Finish();
    45. }
    46. }
    47. }
    48. }
    49. }
  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. <style name="MyTheme" parent="MyTheme.Base">
    6. </style>
    7. <style name="MyTheme.Splash" parent ="Theme.AppCompat.Light.NoActionBar">
    8. <item name="android:windowBackground">@drawable/splash_screen</item>
    9. <item name="android:windowNoTitle">true</item>
    10. <item name="android:windowFullscreen">true</item>
    11. <item name="android:windowContentOverlay">@null</item>
    12. <item name="android:windowActionBar">true</item>
    13. </style>
    14. </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. namespace SharedPreferencesDemo
    7. {
    8. [Activity(Label = "Shared Preferences")]
    9. public class MainActivity : Activity
    10. {
    11. Button btnLogin;
    12. EditText userName, password;
    13. CheckBox mCbxRemMe;
    14. protected override void OnCreate(Bundle bundle)
    15. {
    16. base.OnCreate(bundle);
    17. // Set our view from the "main" layout resource
    18. SetContentView (Resource.Layout.Main);
    19. userName = FindViewById<EditText>(Resource.Id.userNameEditText);
    20. password = FindViewById<EditText>(Resource.Id.passwordEditText);
    21. btnLogin = FindViewById<Button>(Resource.Id.btnLogin);
    22. mCbxRemMe = FindViewById<CheckBox>(Resource.Id.cbxRememberMe);
    23. btnLogin.Click += BtnLogin_Click;
    24. }
    25. private void BtnLogin_Click(object sender, System.EventArgs e)
    26. {
    27. Intent intent = new Intent(this, typeof(LoginSuccessActivity));
    28. User user = new User()
    29. {
    30. UserID = 1,
    31. UserName = userName.Text,
    32. Password = "amit"
    33. };
    34. intent.PutExtra("User", JsonConvert.SerializeObject(user));
    35. if (mCbxRemMe.Checked)
    36. {
    37. ISharedPreferences pref = Application.Context.GetSharedPreferences("UserInfo", FileCreationMode.Private);
    38. ISharedPreferencesEditor edit = pref.Edit();
    39. edit.PutString("Username", userName.Text.Trim());
    40. edit.PutString("Password", password.Text.Trim());
    41. edit.Apply();
    42. }
    43. this.StartActivity(intent);
    44. }
    45. }
    46. }
  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. </LinearLayout>
    71. </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. <item android:state_checked="true"
    4. android:drawable="@android:drawable/checkbox_on_background"/>
    5. <item android:state_checked="false"
    6. android:drawable="@android:drawable/checkbox_off_background"/>
    7. </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.

Summary

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