locked
How to save user settings RRS feed

  • Question

  • User20374 posted

    He guys,

    I would really like to save some user settings like a checkbox or name or something, so that the next time I open my app I don't have to make all the settings again. I found the example below but it's not working. OnSaveInstanceState and OnRestoreInstanceState are never called. I thought they would be called somewhere arround onStop() and onStart()...

    Does anyone can explain to me how to save settings?

    Thanks!

        string myString;
        bool myBool;
    
         protected override void OnSaveInstanceState(Bundle outState)
        {
            outState.PutString("myString", "This is my string");
            outState.PutBoolean("myBool", true);
            base.OnSaveInstanceState(outState);
        }
    
    
        protected override void OnRestoreInstanceState(Bundle savedState)
        {            
            myString = savedState.GetString("myString");
            myBool = savedState.GetBoolean("myBool");
            base.OnRestoreInstanceState(savedState);
    
        }
    
    Sunday, September 22, 2013 12:46 PM

All replies

  • User9089 posted

    Hey @Bass31!

    This type of saving works only by configurationchanges. For example if you rotate your device the application stopped and restarted. If you have a form with name, age, address, etc. The user typed in his name and age, but his address is very long and he want to rotate his device to type his address because his address is too long for portrait mode. In this situtation if you rotate your device it will be called the OnStop and OnStart method i think. And the typed in informations(name, age) will be lost. The user should start again type in everything. This is not a humane procedure. You can save this information temporarely like in your code and nothing will be lost.

    You need another thing. You want to save information between two application starting for example. You have 3 choise: SharedPreferences, File saving, SQLite. With sharedpreferences you can save atomic values(logic, number, string, etc.). With file you can save complexer information. For example an application configuration. You can save your configuration in xml file. With SQLite you can save information like you save your datas in a database. But i think from your code you need now the sharedPreferences: developer.android.com/reference/android/content/SharedPreferences.html

    Monday, September 23, 2013 6:33 AM
  • User20374 posted

    Thanks for your answer.

    I tested the code below and it worked :)

        // 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());
    
        }
    
    Monday, September 23, 2013 6:17 PM
  • User43095 posted

    Wow is great, thanks !!!

    Friday, March 28, 2014 2:19 PM
  • User67129 posted

    This method works great. @Bass31? is this also a safe way to store passwords? e.g. storing UserName and Password? Also is it possible to delete these credentials?

    Monday, August 18, 2014 8:32 AM
  • User20374 posted

    Hey JKay,

    I'm not sure if it safe, but to be sure you could make your own encryption function like changing letters before you safe the credentials and use a decryption function to read them. I just made that up, maybe there are some standard solutions for that.

    You can delete a user name or password to just write an empty string like this: ""

    Example: prefEditor.PutString("UserName", ""); //Delete user name prefEditor.PutString("Password", ""); //Delete password

    Monday, August 18, 2014 9:11 AM
  • User1341 posted

    It is not safe to save plain user credentials in shared preferences. Even in private mode is it possible, with an rooted device, to access that file location.

    Monday, August 18, 2014 12:10 PM
  • User64797 posted

    Thanks for the Registry Save / Restore code.

    Works GREAT!

    :smiley:

    Monday, February 9, 2015 8:54 PM
  • User94701 posted

    Hi, How do I store user settings? I'm wanting to save a url username and address within my app.

    Wednesday, April 1, 2015 2:58 PM
  • User1341 posted

    You can do it like Bass31 has written in this post. Just read. ;-)

    Wednesday, April 1, 2015 3:51 PM
  • User232295 posted

    'Application' does not contain a definition for 'Context'

    :neutral:

    Friday, July 1, 2016 8:06 PM
  • User131380 posted

    @curtis.ehrhart That's because you have to implement it in the Droid project in this example.

    Saturday, August 6, 2016 4:01 AM
  • User256755 posted

    Thanx for the codesample Bass31 .. works like a charm.

    Regards, Ruud

    Sunday, October 9, 2016 5:43 PM
  • User243969 posted

    does it support all platforms or only xamarin.android?

    Wednesday, April 12, 2017 3:37 PM
  • User1341 posted

    It only supports Android.

    Wednesday, April 12, 2017 3:40 PM
  • User193610 posted

    @Bass31 said: Thanks for your answer.

    I tested the code below and it worked :)

        // 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());
    
        }
    

    That is amazing

    Saturday, April 22, 2017 3:09 PM
  • User11724 posted

    You can use "Advexp.Settings Local" ( https://components.xamarin.com/view/advexp-settings-local ) to store any build-in or user-defined types and it collections in NSUserDefaults or KeyChain for iOS and SharedPreferences or KeyStore for Android. Interaction with settings occurs like with any variable or property in C#. This component support iOS, Android and PCL and it is unit tested. Also JSON serialization is supported. Ability to create app settings together with InAppSettingsKit ( https://components.xamarin.com/view/InAppSettingsKit ) and interaction with system Settings App for iOS. For more details see component`s examples.

    Also you can use "Advexp.Settings Cloud" ( https://components.xamarin.com/view/advexp-settings-cloud ). This component has all Advexp.Settings Local functionality + ability to save settings to Amazon Cognito Sync cloud ( http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-sync.html ) and sync them across the different devices (iOS or Android)

    Project site: https://bitbucket.org/advexp/component-advexp.settings

    "Advexp.Settings Local" Xamarin component: https://components.xamarin.com/view/advexp-settings-local "Advexp.Settings Cloud" Xamarin component: https://components.xamarin.com/view/advexp-settings-cloud

    NuGet package “Advexp.Settings Local”: https://www.nuget.org/packages/Advexp.Settings.Local NuGet package “Advexp.Settings Cloud”, evaluation version: https://www.nuget.org/packages/Advexp.Settings.Cloud.Evaluation

    Friday, July 21, 2017 11:15 PM
  • User342099 posted

    using AndroidContext = Android.App; public static void SaveSetting(string key, string value) { var prefs = AndroidContext.Application.Context.GetSharedPreferences(AndroidInfo.ApplicationName.Trim(), FileCreationMode.Private); var prefEditor = prefs.Edit(); prefEditor.PutString(key, value); prefEditor.Commit(); } public static string GetSetting(string key, string defValue = null) { var prefs = AndroidContext.Application.Context.GetSharedPreferences(AndroidInfo.ApplicationName.Trim(), FileCreationMode.Private); var settingValue = prefs.GetString(key, defValue); return settingValue; }

    ``` public class AndroidInfo {

        private static bool IsNetworkAvailable()
        {
            bool isNetworkActive;// = false;
            Context context = Xamarin.Forms.Forms.Context;//get the current application context
            ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
            NetworkInfo activeConnection = cm.ActiveNetworkInfo;
            isNetworkActive = (activeConnection != null) && activeConnection.IsConnected;
            return isNetworkActive;
        }
    
        #region SystemInfo
        public bool IsInternetAvailble
        {
            get { return IsNetworkAvailable(); }
        }
        public  string SystemFamily
        {
            get
            {
                string deviceType = "Mobile";
                var context = Forms.Context;
                var manager = context.GetSystemService(Context.TelephonyService)
                       as TelephonyManager;
    
                if (manager == null)
                {
                    deviceType = "Unknown";
                }
                else if (manager.PhoneType == PhoneType.None)
                {
                    deviceType = "Tablet";
                }
                else
                {
                    deviceType = "Mobile";
                }
                return deviceType;
            }
        }
        public string SystemVersion
        {
            get
            {
                return Build.VERSION.Release;
            }
        }
        public string SystemArchitecture { get { return Build.CpuAbi; } }
        public string ApplicationName
        {
            get
            {
                var context = Forms.Context;
                return context.PackageManager.GetPackageInfo(context.PackageName, 0).PackageName;
            }
        }
        public string ApplicationVersion
        {
            get
            {
                var context = Forms.Context;
                return context.PackageManager.GetPackageInfo(context.PackageName, 0).VersionName;
            }
        }
        public string DeviceManufacturer
        {
            get
            {
                return Build.Manufacturer;
            }
        }
        public string DeviceModel { get { return Build.Model; } }
        public string DeviceType
        {
            get
            {
                string deviceType = "Mobile";
                var context = Forms.Context;
                var manager = context.GetSystemService(Context.TelephonyService)
                       as TelephonyManager;
                if (manager == null)
                {
                    deviceType = "Unknown";
                }
                else if (manager.PhoneType == PhoneType.None)
                {
                    deviceType = "Tablet";
                }
                else
                {
                    deviceType = "Mobile";
                }
                return deviceType;
            }
        }
        public string FreeSpace()
        {
            var activityManager = (ActivityManager)Forms.Context.GetSystemService(Context.ActivityService);
            ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
            activityManager.GetMemoryInfo(memInfo);
            var free = (memInfo.AvailMem / 1024 / 1024);
            return free.ToString();
        } 
        #endregion
    }
    

    ```

    Sunday, November 12, 2017 8:30 AM
  • User342099 posted

    Save settings of any value type

    ~~~~ ///

    /// Save string to local setting /// /// /// public static void SaveLocalSetting(string key, object value) { var prefs = AndroidContext.Application.Context.GetSharedPreferences(Application.Context.PackageName, FileCreationMode.Private); var prefEditor = prefs.Edit(); Type type = value.GetType(); if(type.Equals(typeof(string))) prefEditor.PutString(key, (string)value); else if (type.Equals(typeof(int))) prefEditor.PutInt(key, (int)value); else if (type.Equals(typeof(bool))) prefEditor.PutBoolean(key, (bool)value); else if (type.Equals(typeof(float))) prefEditor.PutFloat(key, (float)value); else if (type.Equals(typeof(long))) prefEditor.PutLong(key, (long)value); else if (type.Equals(typeof(double))) prefEditor.PutString(key, value.ToString() + "typeofdoubleOTIJoPgF5ZIjviz8"); else throw new Exception("Value not supported to save settings!"); prefEditor.Commit(); } /// /// Get object from local setting /// /// /// public static object GetLocalSetting(string key) { object obj = null; var prefs = AndroidContext.Application.Context.GetSharedPreferences(Application.Context.PackageName, FileCreationMode.Private); var settingList = prefs.All; if (settingList.TryGetValue(key, out obj)) { if (obj.GetType().Equals(typeof(string)) && obj.ToString() == obj.ToString() + "typeofdoubleOTIJoPgF5ZIjviz8") return Convert.ToDouble(obj.ToString().Replace("typeofdoubleOTIJoPgF5ZIjviz8", "")); return obj; }
    return obj; } ~~~~

    Saturday, August 10, 2019 4:59 AM