Академический Документы
Профессиональный Документы
Культура Документы
Home
About us
Contact us
Privacy Policy
Tutorials
Gadgets
Internet
Technologies
http://techblogon.com/android-sharedpreferences-example-code/
1/15
15/07/2015
Store your applications data on the web with your own network server. So that other users can access it when
required.
Internal Storage
Store your applications private data on the phone memory (device memory)
External Storage
Store your applications data on the shared external storage, so that other application can be access it if
required.
Now it is enough for some basic idea about data storing in Android. Lets come to our main focus e.g. Android
SharedPreferences example with source code description
To make this Android shared preference example very simple, we will use different Android primitive data types
like: boolean, float, int, long, and string etc and store some user data into Android SharedPreference. Then we
will retrieve (fetch) those stored data from Android SharedPreferences.
Note: Android SharedPreferences uses only Key-Value pair for storing data, that means, when we will store
data to Android SharedPreferences, we will use a unique key and some corrosponding data with that key.
2/15
15/07/2015
Step 1: Create a new Shared Preferences file in your Android application. We will open it if it is already exist.
We will use the function getSharedPreferences() function from the inbuilt Android class.
Step 2: For getting data from the Android SharedPreferences file, we will use functions like getString(),
getInt() etc.
Step 3: For storing the data, we need to use the Android Editor Class SharedPreferences.Editor. Then we
will store data into the Android SharedPreferences file using functions putString(), putInt() etc. then commit the
whole data using commit() function.
Note: In the above code snippet, to make the code buildable please change float value, long value to the
real float and long values.
3/15
15/07/2015
If you want to clear (delete) all data at a time then you can use the below code snippet.
1 editor.clear(); // clear all data.
2 editor.commit(); // commit changes
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
http://techblogon.com/android-sharedpreferences-example-code/
4/15
15/07/2015
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:hint="SharedPreference Example"
android:ems="10" >
</TextView>
<EditText
android:id="@+id/editTextEnterName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:maxLength="30"
android:hint="Enter Your Name">
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextEnterEid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:maxLength="8"
android:inputType ="number"
android:hint="Enter Your Employee ID">
</EditText>
<EditText
android:id="@+id/editTextEnterAge"
android:layout_width="fill_parent"
android:layout_marginTop="10dp"
android:inputType ="number"
android:maxLength="2"
android:layout_height="wrap_content"
android:hint="Enter Your Age">
</EditText>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:gravity="center_horizontal">
<Button
android:id="@+id/buttonStore"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="onClickStore"
android:text="Store" />
<Button
http://techblogon.com/android-sharedpreferences-example-code/
5/15
15/07/2015
63
64
65
66
67
68
69
70
71
android:id="@+id/buttonLoad"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_toRightOf="@+id/buttonStore"
android:onClick="onClickLoad"
android:text="Load" />
</RelativeLayout>>
</LinearLayout>
package com.techblogon.sharedpreferenceexample;
import android.content.Context;
import android.content.SharedPreferences;
// all methods are static , so we can call from any where in the code
//all member variables are private, so that we can save load with our own fun only
public class SharedPrefManager {
//this is your shared preference file name, in which we will save data
public static final String MY_EMP_PREFS = "MySharedPref";
// will get user input in below variables, then will store in to shared pref
private static String
mName
= "";
private static String
mEid
= "";
private static int
mAge
= 0;
http://techblogon.com/android-sharedpreferences-example-code/
6/15
15/07/2015
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
7. Add the below default Activity Java file (MainActivity.Java) , which contains all GUI part and will use all
SharedPreferences functions from this class.
In this class we called SharedPrefManager.Init(this) function from the OnCreate() of the activity. Then we will
Store and Load user data when user click on the buttons called Store and Load. Here you can find functions
like onClickLoad() and onClickStore(), where we will store and load user data. So first we will get user data
http://techblogon.com/android-sharedpreferences-example-code/
7/15
15/07/2015
and pass all user data to the SharedPrefManager class using its own functions, then we will store all data at a
time using SharedPrefManager classs function SharedPrefManager.StoreToPref(). Similarly we will
use SharedPrefManager.LoadFromPref().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.techblogon.sharedpreferenceexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPrefManager.Init(this);
}
public void onClickStore(View v) {
//get user input first, then store. we will use our SharedPrefManager Class functions
EditText editTextName,editTextEmpID,editTextAge;
editTextName=(EditText)findViewById(R.id.editTextEnterName);
editTextEmpID=(EditText)findViewById(R.id.editTextEnterEid);
editTextAge=(EditText)findViewById(R.id.editTextEnterAge);
if(0!= srtTextName.length())
SharedPrefManager.SetName(srtTextName); // need string value so convert it
if(0 !=srtTextEmpID.length())
SharedPrefManager.SetEmployeeID(srtTextEmpID); // need string value so convert it
if(0 != strTextAge.length())
SharedPrefManager.SetAge(Integer.parseInt(strTextAge)); // need integer value so convert it
//now save all to shared pref, all updated values are now available in SharedPrefManager cl
SharedPrefManager.StoreToPref();
//reset all fields to blank before load and update from sharedpref
EditText tv = null;
tv = (EditText)findViewById(R.id.editTextEnterName);
tv.setText("");
tv = (EditText)findViewById(R.id.editTextEnterEid);
tv.setText("");
tv = (EditText)findViewById(R.id.editTextEnterAge);
tv.setText("");
}
public void onClickLoad(View v) {
http://techblogon.com/android-sharedpreferences-example-code/
8/15
15/07/2015
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.techblogon.sharedpreferenceexample.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
9/15
15/07/2015
http://techblogon.com/android-sharedpreferences-example-code/
10/15
15/07/2015
I hope this tutorial on Android SharedPreferences Example will help you at its best.
Previous Page
Android Tutorial Home Page
Next Page
C ONNECT
Anil says:
April 15, 2013 at 6:10 am
Hi SmrutiRanjan,
I am regular reader of your android tutorial thanks for your tutorial and its very useful for me. On the
above article you have mention string is primitive date type. Is String is primitive data type in java? or we
can userdefind date types into SharedPreferences. Please explain.
Regards,
Anil Kumar
Reply
SmrutiRanjan says:
April 16, 2013 at 3:51 pm
Make sure to turn on Auto rotation feature in your phone.
It will work 100%.
Reply
SmrutiRanjan says:
April 16, 2013 at 4:09 pm
http://techblogon.com/android-sharedpreferences-example-code/
11/15
15/07/2015
Yes, String is primitive data type in java. you can save in sharedpref.
User defined data type is nothing but collection of primitive data types, so you can write a small
logic ff you want to save user define data types in sharedpref.
That means, iterate into the user define data type and save individual data. Also for more complex
data it is better to use SQLite database
Reply
2.
3.
4.
EKTA says:
June 29, 2013 at 4:24 pm
sir i need a full code of android in a zip file which will import data that already existing on sqlite database,i
want to only retrieve that data.i tried many codes but its not working.
Reply
5.
alloice says:
July 1, 2013 at 2:38 pm
can i get a code for a shopping cart in android that picks items from the database?????
Reply
6.
Sundaramoorthy says:
November 13, 2013 at 4:59 am
http://techblogon.com/android-sharedpreferences-example-code/
12/15
15/07/2015
I am doing android facebook integration. I need to store authentication information into device account.
Anyone help please. Is it possible ??
Reply
Leave a Reply
Your email address will not be published. Required fields are marked *
Name *
Email *
Website
1
= one
Comment
You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym
title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del
datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" dataurl=""> <span class="" title="" data-url="">
Post Comment
http://techblogon.com/android-sharedpreferences-example-code/
13/15
15/07/2015
Search
Techblogon
Follow
+1
+ 305
Like 1,859 people like this. Be the first of your friends.
12
Recommend on Google
Follow @techblogon
RSS Feed
Google Plus
Archives
March 2015
July 2014
April 2014
October 2013
August 2013
July 2013
June 2013
May 2013
April 2013
March 2013
February 2013
January 2013
December 2012
Categories
Android
Android Tutorial
Design Patterns
Displays
E-Commerce
http://techblogon.com/android-sharedpreferences-example-code/
14/15
15/07/2015
Gadgets
Google
Internet
Mobile Phones
Softwares
Technologies
Tutorials
Windows
Pages
About us
Contact us
Privacy Policy
Meta
Log in
Entries RSS
Comments RSS
WordPress.org
2015 Techblogon
http://techblogon.com/android-sharedpreferences-example-code/
15/15