Rupesh Kahane

Rupesh Kahane

  • 95
  • 19.1k
  • 4.1m

Xamarin Android App Not Persist Any State (Session)

Nov 29 2016 9:03 AM
I have one simple layout1 which contains one EditText and Two button.
 
On first button click I am just saving the user text value using Shared Preferences.
and on second button click,showing another layout 2.
 
I would like to maintain (Persist state) in Xamarin Android App from one layout to another layout.
 
I have used ISharedPreferences but it is not Persist any state.
 
Below is my code for layout1
  1. public class MainActivity : Activity  
  2.   {  
  3.       protected override void OnCreate(Bundle bundle)  
  4.       {  
  5.           ISharedPreferences sharedPrefernce;  
  6.           base.OnCreate(bundle);  
  7.   
  8.           SetContentView(Resource.Layout.Main);  
  9.   
  10.           Button button = FindViewById<Button>(Resource.Id.btnAdd);  
  11.   
  12.           button.Click += delegate  
  13.           {  
  14.               EditText nameBox = FindViewById<EditText>(Resource.Id.editText1);  
  15.               string name = nameBox.Text.ToString();  
  16.   
  17.                 
  18.               var lc = Application.Context.GetSharedPreferences("MyContacts", FileCreationMode.Private);  
  19.               var cEdit = lc.Edit();  
  20.               cEdit.PutString("Name", name);                  
  21.               cEdit.Apply();                 
  22.   
  23.               Android.Widget.Toast.MakeText(this"Item Added", ToastLength.Short).Show();  
  24.               nameBox.Text = "";  
  25.           };  
  26.   
  27.           Button viewContact = FindViewById<Button>(Resource.Id.btnShowData);  
  28.             
  29.           viewContact.Click += delegate  
  30.           {                  
  31.               SetContentView(Resource.Layout.ViewContactsActivity);  
  32.           };  
  33.       }  
Below is my code for layout2
  1. protected override void OnCreate(Bundle savedInstanceState)  
  2.        {  
  3.                var textView3 = FindViewById<TextView>(Resource.Id.textView3);  
  4.                try  
  5.                {  
  6.                    var lc = Application.Context.GetSharedPreferences("MyContacts", FileCreationMode.Private);  
  7.                    string retrivedName = lc.GetString("Name"null);                      
  8.                    textView3.Text = retrivedName.ToString();  
  9.                }  
  10.                catch (System.Exception ex)  
  11.                {  
  12.                    textView3.Text = ex.Message.ToString();  
  13.                }  
  14.        }  
Please suggest me How to persist a state in Xamarin Android App.
Thanks 

Answers (1)