Forum Xamarin.Android

How to save user settings

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);

    }

Posts

  • CortezCortez USMember ✭✭✭

    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

  • PauloDiasPauloDias BRMember

    Wow is great, thanks !!!

  • JKayJKay USMember ✭✭✭
    edited August 2014

    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?

  • Bass31Bass31 USMember ✭✭

    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

  • SebastianSeidel.9226SebastianSeidel.9226 DEInsider, University ✭✭✭✭

    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.

  • Thanks for the Registry Save / Restore code.

    Works GREAT!

    :smiley:

  • Craig.4350Craig.4350 USMember

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

  • SebastianSeidel.9226SebastianSeidel.9226 DEInsider, University ✭✭✭✭

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

  • curtis.ehrhartcurtis.ehrhart USMember ✭✭

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

    :neutral:

  • SweeHengCheahSweeHengCheah USMember ✭✭

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

  • RuudAaldersRuudAalders USMember

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

    Regards, Ruud

  • HistoryaHistorya USMember ✭✭✭

    does it support all platforms or only xamarin.android?

  • SebastianSeidel.9226SebastianSeidel.9226 DEInsider, University ✭✭✭✭

    It only supports Android.

  • DavDeveloperDavDeveloper USMember

    @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

  • Alexey_IvakinAlexey_Ivakin BYMember ✭✭

    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

  • LearnEverythingLearnEverything USMember ✭✭✭
    edited November 2017
    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
        }
    
  • LearnEverythingLearnEverything USMember ✭✭✭
    edited August 2019

    Save settings of any value type

    /// <summary>
            /// Save string to local setting 
            /// </summary>
            /// <param name="key"></param>
            /// <param name="value"></param>
            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();
            }
            /// <summary>
            /// Get object from local setting
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            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;
            }
    
Sign In or Register to comment.