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
- public class MainActivity : Activity
- {
- protected override void OnCreate(Bundle bundle)
- {
- ISharedPreferences sharedPrefernce;
- base.OnCreate(bundle);
-
- SetContentView(Resource.Layout.Main);
-
- Button button = FindViewById<Button>(Resource.Id.btnAdd);
-
- button.Click += delegate
- {
- EditText nameBox = FindViewById<EditText>(Resource.Id.editText1);
- string name = nameBox.Text.ToString();
-
-
- var lc = Application.Context.GetSharedPreferences("MyContacts", FileCreationMode.Private);
- var cEdit = lc.Edit();
- cEdit.PutString("Name", name);
- cEdit.Apply();
-
- Android.Widget.Toast.MakeText(this, "Item Added", ToastLength.Short).Show();
- nameBox.Text = "";
- };
-
- Button viewContact = FindViewById<Button>(Resource.Id.btnShowData);
-
- viewContact.Click += delegate
- {
- SetContentView(Resource.Layout.ViewContactsActivity);
- };
- }
Below is my code for layout2
- protected override void OnCreate(Bundle savedInstanceState)
- {
- var textView3 = FindViewById<TextView>(Resource.Id.textView3);
- try
- {
- var lc = Application.Context.GetSharedPreferences("MyContacts", FileCreationMode.Private);
- string retrivedName = lc.GetString("Name", null);
- textView3.Text = retrivedName.ToString();
- }
- catch (System.Exception ex)
- {
- textView3.Text = ex.Message.ToString();
- }
- }
Please suggest me How to persist a state in Xamarin Android App.
Thanks