Android

Android Shared Preferences Example with source code
Author : Ishtek

Using Android API Level : 7 
In the following example we shall look and explore Android's Shared Preferences
feature with the help of an example.

SharedPreferences class file from Android API can be used to store/retrieve/modify etc
the preferences returned by the getSharedPreferences method of the Context object.
As an Activity is a subclass to the Context class, so this method getSharedPreferences
would be directly accessible to the user defined activity class as well.

getSharedPreferences(String, int) with the first argument is for the name of the file
that is to be used (if present in appropriate folder), or create a new one with 
appropriate mode as mentioned in the second argument of type int.

There are various mode available while writing this page are as follows:
MODE_PRIVATE
MODE_WORLD_READABLE
MODE_WORLD_WRITEABLE
MODE_MULTI_PROCESS (Please refer Android Official documentation for details whether this
                    mode is supported or not)

Context.getSharedPreferences method returns an instance of SharedPreferences.

If you want to read any stored value then you can use SharedPreferences object,
but if you are going to put/change/remove any content from this object, then you
have to get an handle to the SharedPreferences.Editor object in order to carry out
any changes in the preferences.

A sample example on the very concept of providing shared preferences feature to 
an appplication on Android Platform.

This example application is having a very simple UI, with three text views, one
for BLUE, another for RED and the third one for showing the selected text view
TEXT on screen. Objective of this example is to show a way by which small bit of
data in form of string vale, can be stored in some form by using shared preferences
api provided by Android API.

UI screen snapshot is as follows:



The main activity code of this example is as follows:

SharedPreferenceActivity.java
/** * This code is provided on "AS IS" basis without guarantee/warranty * of any kind. Use of this code subjected to user's own risk. * @Author: Ishtek at usingframeworks@gmail.com * @Date : 2nd Mar 2013. */ package com.example.sharedpreferenceproject; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.TextView; public class SharedPreferenceActivity extends Activity implements OnTouchListener{ private TextView textView3; private SharedPreferences sp; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shared_preference); TextView txtView1 = (TextView) findViewById(R.id.txtView1); txtView1.setOnTouchListener(this); TextView txtView2 = (TextView) findViewById(R.id.txtView2); txtView2.setOnTouchListener(this); textView3 = (TextView) findViewById(R.id.txtView3); sp = getSharedPreferences("sample", Context.MODE_APPEND); if(!sp.getString("color_type", "").equalsIgnoreCase("")){ textView3.setText(sp.getString("color_type", "")); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_shared_preference, menu); return true; } public boolean onTouch(View arg0, MotionEvent arg1) { if(arg0.getTag().equals("blue")) { SharedPreferences.Editor editor = sp.edit(); editor.putString("color_type", "BLUE"); editor.commit(); } if(arg0.getTag().equals("red")) { SharedPreferences.Editor editor = sp.edit(); editor.putString("color_type", "RED"); editor.commit(); } if(!sp.getString("color_type", "").equalsIgnoreCase("")){ textView3.setText(sp.getString("color_type", "")); } return false; } }
activity_shared_preference.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TableRow android:id="@+id/tableRow1"> <TextView android:id="@+id/txtView1" android:tag="blue" android:text="@string/txt_label1" android:textSize="20dp" android:textStyle="bold" android:layout_width="80dp" android:background="#0000ff"/> <TextView android:id="@+id/txtView2" android:tag="red" android:text="@string/txt_label2" android:textSize="20dp" android:textStyle="bold" android:layout_width="80dp" android:background="#ff0000"/> </TableRow> <TableRow android:id="@+id/tableRow2"> <TextView android:id="@+id/txtView3" android:tag="status" android:text="" android:textSize="20dp" android:textStyle="bold" android:layout_width="fill_parent"/> </TableRow> </TableLayout>
strings.xml
<string name="txt_label1">BLUE</string> <string name="txt_label2">RED</string>
After setting up various files of this example and running the main activity class, the UI screen appears. One clicking/touching any of the text views, either BLUE or RED, accordingly the label "BLUE" or "RED" would get stored in the shared preferences of the emulator. While using ADT Plugin Emulator, a file with the name as mentioned in the code (i.e, sample.xml) can be found under, data/data/com.example.sharedpreferenceproject/shared_prefs/sample.xml sample.xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="color_type">RED</string> </map>
In the above file, RED is the value for the key as color_type, now by touching/clicking BLUE text on screen, this string value can be changed to BLUE. The activity code here reads the value from the shared preferences file and sets appropriate value in the textview (onCreate method has the code for this).
If interested in commenting related to Android SharedPreferences Example
Click Here

Name (To be shown on this Page:*

Email (Not to be shown):*

Website (To be shown on this Page)

Your Comments here (To be shown on this Page):*

(You can use <a> Tag in your comments)

Please enter same number as shown here 183




Android Thread Example

REST Interview Questions

JAX-WS Webservice Example

Android Overlap SurfaceView Example

Spring3 Integration of File Endpoint

JAXWS Webservice Example

Android WebView Example

Android Context Menu Example

Setting up Eclipse for Android App Development

Android SensorEvent Orientation Example

Android ImageSwitcher Example

REST API Design for Android App

Android ExpandableListView Example

Singleton Serializable on Android

Android GPS with Google MAP Example

Android Project With Example

Android Project Manageing Files

Project Ideas for App on Android Platform

Android EditText with Background

Android SQLite Database Example

Android AutoCompleteTextView Example

Android Tester

Android Interview Questions

Android ListView Example

Android Intent Notification Example

Android Intent Broadcast Example

Android TextView Link Example

Android Sensor List

Android Sensor Orientation Example

Android Intent Broadcast Receiver

Android Gallery SurfaceViews Example

Android Location Example

Android Text to Speech Example

Android Intent Example

Android Layout Example

Android Download File Example

Android Expandable ListView Example

Android Tab Example

Android RelativeLayout Example

Android Intent Example

Android Text to Speech Example

Android SQLite Example

Android CustomView Example

Android Canvas Example

Android SharedPreferences Example

Android Shape Background Example

Android ShapeButton Example

Android ViewFlipper Example

Android Gallery Example

Android TimePickerDialog Example





If interested commenting on this Page :

comments powered by Disqus
Any source code found on any of the page(s) in Techiecommunity.net is associated with following notice: 
   /*
     * TECHIECOMMUNITY.NET MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
     * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
     * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
     * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. TECHIECOMMUNITY.NET SHALL NOT BE LIABLE FOR
     * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
     * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
     *
     * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
     * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
     * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
     * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
     * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
     * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
     * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). TECHIECOMMUNITY.NET
     * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
     * HIGH RISK ACTIVITIES.
     */
   
The content provided in this page is NOT warranted and/or NOT guaranteed by techiecommunity.net .
techiecommunity.net is not liable for any negative consequences that may result/arise from 
implementing directly/indirectly any information covered in these pages/articles/tutorials.

For any of the content, if you would like to bring it to notice for removal from this web site, 
please write to this web site administrator @ EMAIL-ID (please remove space before and after @),
with appropriate concern and supporting proof(s). After thorough review and if found genuine concern,
we would take appropriate action and remove disputed content from this web site within 24 hours 
starting from the time it has brought to techiecommunity.net Administrator notice.

This website uses cookies and third party cookies to improve the user experience. 
And to provide more relevant ads. 
In case of continued use of this website implies that you accept the use of cookies on this website.
		
While using this web site, you agree to have read and accepted techiecommunity.net terms of use and privacy policy.