{"id":25082,"date":"2015-08-04T15:14:38","date_gmt":"2015-08-04T09:44:38","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=25082"},"modified":"2024-01-02T17:48:48","modified_gmt":"2024-01-02T12:18:48","slug":"shared-preferences-in-android","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/shared-preferences-in-android\/","title":{"rendered":"Shared Preferences in Android"},"content":{"rendered":"<p style=\"text-align: center\"><strong>Shared Preferences in Android<br \/>\n<\/strong><\/p>\n<p>Android Prefereces provide a way to store user and application data in device. It stores primitive data including String objects in key-value pairs.<\/p>\n<p>There are several ways to store data in android:<\/p>\n<ol type=\"1\">\n<li><strong>Preferences(Shared and User)<\/strong>:<br \/>\nStore private primitive data in key-value pairs.<\/li>\n<li><strong>Internal Storage<\/strong>:<br \/>\nStore private data on the device memory.<\/li>\n<li><strong>External Storage<\/strong>:<br \/>\nStore public data on the shared external storage.<\/li>\n<li><strong>SQLite database<\/strong>:<br \/>\nStore structured data in a private database.<\/li>\n<li><strong>Content Provider:<\/strong><br \/>\nShare data with other apps Shared Preferences<\/li>\n<\/ol>\n<p><strong>Shared Preferences(Permanent Storage):<\/strong><\/p>\n<ul type=\"disc\">\n<li>Very simple way of share small amount of data between activities. Also for saving the state of the app. Preferences can stores only primitive types of data.<\/li>\n<li>Preferences can be private or public (world readable, writeable)(deprecated from Api 17)<\/li>\n<li>To get SharedPreferences, use<br \/>\n\u2013 getSharedPreferences(String name) (if multiple pref. files)<br \/>\n\u2013 getPreferences() (if only one pref. File is needed)<\/li>\n<li>To write values, call edit() to get SharedPreferences.Editor to be used when adding values to file.<\/li>\n<\/ul>\n<p><strong>Example:<\/strong><\/p>\n<p>[code language=&#8221;java&#8221;]<br \/>\npublic void savePreferences(){<br \/>\n     SharedPreferences mySPref = getSharedPreferences(MYPREFS,0);<br \/>\n     SharedPreferences.Editor editor = mySharedPreferences.edit();<br \/>\n     editor.putBoolean(&quot;isTrue&quot;, true);<br \/>\n     editor.putString(&quot;EntryValue&quot;, &quot;Not Empty&quot;);<br \/>\n     editor.commit();<br \/>\n}<\/p>\n<p>public void loadPreferences() {<br \/>\n     SharedPreferences mySPref = getSharedPreferences(MYPREFS,0);<br \/>\n     boolean isTrue = mySharedPreferences.getBoolean(&quot;isTrue&quot;, false);<br \/>\n     String stringPref = mySharedPreferences.getString(&quot;EntryValue&quot;,&quot;&quot;);<br \/>\n}<br \/>\n[\/code]<\/p>\n<p><strong>What getSharedPreferences() does?<\/strong><\/p>\n<p>[code language=&#8221;java&#8221;]<br \/>\npublic abstract SharedPreferences getSharedPreferences (String name, int mode)<br \/>\n[\/code]<\/p>\n<ul type=\"square\">\n<li><strong>returns:<\/strong> One instance of the SharedPrefrences.<\/li>\n<li><strong>name:<\/strong> Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor.<\/li>\n<li><strong>mode:<\/strong> Operating mode.<\/li>\n<li>0 or <strong>MODE_PRIVATE<\/strong> for the default operation.<br \/>\n<strong>MODE_WORLD_READABLE<\/strong>, <strong>MODE_WORLD_WRITEABLE<\/strong>,<br \/>\n<strong>MODE_MULTI_PROCESS<\/strong> used if multiple processes are mutating the same SharedPreferences file.<\/li>\n<\/ul>\n<p><strong>The <a href=\"http:\/\/developer.android.com\/reference\/android\/preference\/PreferenceManager.html#getSharedPreferences()\">getSharedPreferences()<\/a>&#8211;<\/strong> is Context class&#8217;s method. Use this if you need multiple preferences files identified by name, which you specify with the first parameter.<\/p>\n<p><strong>The <a href=\"http:\/\/developer.android.com\/reference\/android\/app\/Activity.html#getPreferences(int)\">getPreferences(int MODE)<\/a><\/strong> method uses the <a href=\"http:\/\/developer.android.com\/reference\/android\/preference\/PreferenceManager.html#getSharedPreferences()\">getSharedPreferences()<\/a> method with the name of the activity class for the preference file name. (for user prefrences). scope limited to activity where it is created.<\/p>\n<p>So if you want the preference to be available in another activity or context, you have to use either of <a href=\"http:\/\/developer.android.com\/reference\/android\/preference\/PreferenceManager.html#getSharedPreferences()\">getSharedPreferences()<\/a> or <a href=\"http:\/\/developer.android.com\/reference\/android\/preference\/PreferenceManager.html#getDefaultSharedPreferences(android.content.Context)\">PreferenceManager.getDefaultSharedPreferences(context)<\/a><\/p>\n<p><strong>Listeners in SharedPreference:<\/strong><\/p>\n<p>SharedPreferences keeps listeners in a WeakHashMap. This means that you cannot use an anonymous inner class as a listener, as it will become the target of garbage collection as soon as you leave the current scope.<\/p>\n<p>[code language=&#8221;java&#8221;]<br \/>\npublic abstract void registerOnSharedPreferenceChangeListener (OnSharedPreferenceChangeListener listener)<\/p>\n<p>public abstract void unregisterOnSharedPreferenceChangeListener (OnSharedPreferenceChangeListener listener)<br \/>\n[\/code]<\/p>\n<p><strong>commit() vs. apply()<\/strong><\/p>\n<ul type=\"disc\">\n<li><a href=\"http:\/\/developer.android.com\/reference\/android\/content\/SharedPreferences.Editor.html#apply()\">apply()<\/a> is asynchronous and commit() is synchronous.<\/li>\n<li><a href=\"http:\/\/developer.android.com\/reference\/android\/content\/SharedPreferences.Editor.html#apply()\">apply()<\/a> does not return boolean value and commit() returns.<\/li>\n<li><a href=\"http:\/\/developer.android.com\/reference\/android\/content\/SharedPreferences.Editor.html#commit()\">commit()<\/a> will block until all async commits are completed.<\/li>\n<\/ul>\n<p><strong>getSharedPreferences() vs getPreferences() vs getDefaultPreferences()<\/strong><\/p>\n<p>getSharedPreferences(String name, int mode) method of the Context class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.<\/p>\n<p><strong>User Preferences(private to Activity):<\/strong><\/p>\n<ul type=\"disc\">\n<li>Shared preferences are not strictly for saving <em>&#8220;user preferences,&#8221;<\/em> such as what ringtone a user has chosen. If you&#8217;re interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).<\/li>\n<li>These preferences can only be used within the particular activity.<\/li>\n<li>PreferenceActivity is the base class for an activity to show a hierarchy of preferences to the user.<\/li>\n<li>It is generally used for saving the setting\/preference of User<\/li>\n<\/ul>\n<p><strong>Steps to create user preference:<\/strong><\/p>\n<ul type=\"disc\">\n<li>Create xml resource for Preference.<\/li>\n<li>Create a Class which extends PreferenceActivity class , and inflate the created xml using addPreferencesFromResource() method.<\/li>\n<li>Call\/Start the PreferenceActivity (created in 2nd steps) from where you want.<\/li>\n<\/ul>\n<p><strong>PrefrenceActivity and PreferenceFragment:<\/strong><br \/>\nPreferenceActivity is the base class for an activity to show a hierarchy of preferences to the user. Prior to HONEYCOMB this class only allowed the display of a single set of preference; this functionality should now be found in the new PreferenceFragment\u00a0class.<\/p>\n<p><span id=\"hs-cta-wrapper-1bf6c096-779b-423a-8642-4bab9532eb73\" class=\"hs-cta-wrapper\"><span id=\"hs-cta-1bf6c096-779b-423a-8642-4bab9532eb73\" class=\"hs-cta-node hs-cta-1bf6c096-779b-423a-8642-4bab9532eb73\"> <a href=\"http:\/\/cta-redirect.hubspot.com\/cta\/redirect\/481864\/1bf6c096-779b-423a-8642-4bab9532eb73\"><img decoding=\"async\" id=\"hs-cta-img-1bf6c096-779b-423a-8642-4bab9532eb73\" class=\"hs-cta-img aligncenter\" style=\"border-width: 0px\" src=\"https:\/\/no-cache.hubspot.com\/cta\/default\/481864\/1bf6c096-779b-423a-8642-4bab9532eb73.png\" alt=\"Secure Coding in Android\" \/><\/a><br \/>\n<\/span><br \/>\n\/\/<br \/>\n<\/span><br \/>\n<!-- end HubSpot Call-to-Action Code --><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Shared Preferences in Android Android Prefereces provide a way to store user and application data in device. It stores primitive data including String objects in key-value pairs. There are several ways to store data in android: Preferences(Shared and User): Store private primitive data in key-value pairs. Internal Storage: Store private data on the device memory. [&hellip;]<\/p>\n","protected":false},"author":184,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":4},"categories":[518,1772],"tags":[4845,476,2166],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/25082"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/184"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=25082"}],"version-history":[{"count":1,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/25082\/revisions"}],"predecessor-version":[{"id":59889,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/25082\/revisions\/59889"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=25082"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=25082"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=25082"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}