Search code examples
c#androidxamarincheckboxactivity-lifecycle

Save checkbox state android xamarin


I am new on xamarin and i am trying to save my checkbox state even if the app is closed because when i close it the checkbox reset to uncheck state...

also.. the image that was changed resets.. is there any way to preserve both?

 protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        SetContentView(Resource.Layout.layout1);

        var seletor = FindViewById<CheckBox>(Resource.Id.checkBox1);
        var imagem = FindViewById<ImageView>(Resource.Id.imageView1);

        seletor.Click += (o, e) => {
            if (seletor.Checked)
                imagem.SetImageResource(Resource.Drawable.estado1);

            else
                imagem.SetImageResource(Resource.Drawable.estado2);

        };
    }

Solution

  • Have you tried to use the Preferences?

    Check the following: How to save user settings

    Store the option selected onclose or suspend.. and retrieve onResume / OnLoad

    Something like:

     // Function called from OnDestroy
    protected void saveset(){
    
        //store
        var prefs = Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private);
        var prefEditor = prefs.Edit();
        prefEditor.PutString("PrefName", "Some value");
        prefEditor.Commit();
    
    }
    
    // Function called from OnCreate
    protected void retrieveset()
    {
        //retreive 
        var prefs = Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private);              
        var somePref = prefs.GetString("PrefName", null);
    
        //Show a toast
        RunOnUiThread(() => Toast.MakeText(this, somePref, ToastLength.Long).Show());
    
    }
    

    as in the link provided.

    Of course you'll need to adapt to your needs and get / populate the value of the checkbox.

    If you want, you can also implement some kind of db and use the same mechanism to persist and retrieve settings.

    This is usually what I use to store settings and persist values that I need to "remember"

    This is an example of how I'm using the same behavior in one app.. not for a checkbox.. but you can see how it works. I removed some code, but I think should be a good example.

    [Activity(Label = "@string/ApplicationName",
            Icon = "@drawable/Icon")]
        public class PersonalDetailsActivity : Activity
        {
            ...
            private ISharedPreferencesEditor prefEditor;
            private ISharedPreferences preferences;
            ...
    
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
    
                SetContentView(Resource.Layout.PersonalDetailView);
    
                preferences = Application.Context.GetSharedPreferences("AppName", FileCreationMode.Private);
    
    
                PopulatePersistedData();
            }
    
            private void PopulatePersistedData()
            {
                myId = preferences.GetInt(nameof(myData.Id), 0);
    
                name.Text = preferences.GetString(nameof(myData.Name), null);
                address.Text = preferences.GetString(nameof(myData.Address), null);
                city.Text = preferences.GetString(nameof(myData.City), null);
                county.Text = preferences.GetString(nameof(myData.County), null);
                emailAddress.Text = preferences.GetString(nameof(myData.Email), null);
                phoneNumber.Text = preferences.GetString(nameof(myData.PhoneNumber), null);
                bio.Text = preferences.GetString(nameof(myData.Bio), null);
                rating.Rating = 5;
    
            }
    
            private void SaveButton_Click(object sender, EventArgs e)
            {
                prefEditor = preferences.Edit();
    
                myData = new Citizen();
    
                myData.Name = name.Text;
                myData.Address = address.Text;
                myData.City = city.Text;
                myData.County = county.Text;
                myData.Email = emailAddress.Text;
                myData.PhoneNumber = phoneNumber.Text;
                myData.Bio = bio.Text;
    
                prefEditor.PutInt(nameof(myData.Id), myId);
                prefEditor.PutString(nameof(myData.Name), myData.Name);
                prefEditor.PutString(nameof(myData.Address), myData.Address);
                prefEditor.PutString(nameof(myData.City), myData.City);
                prefEditor.PutString(nameof(myData.County), myData.County);
                prefEditor.PutString(nameof(myData.Email), myData.Email);
                prefEditor.PutString(nameof(myData.PhoneNumber), myData.PhoneNumber);
                prefEditor.PutString(nameof(myData.Bio), myData.Bio);
    
                prefEditor.Apply();
                prefEditor.Commit();
    
                var intent = new Intent();
                intent.PutExtra("CitizenName", name.Text);
    
                SetResult(Result.Ok, intent);
                this.Finish();
            }
        }