Upload
vairamoorthy-arunachalam
View
238
Download
0
Embed Size (px)
Citation preview
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
1/15
Home
About us
Contact us
Privacy Policy
Tutorials »
Gadgets »
Internet »
Technologies »
Android SharedPreferences Example Code(Save User Data)
April 3, 2013 Android Tutorial, Tutorials
Simple Android SharedPreferences Example with Code Description
Here we will discuss about Android SharedPreferences example with source code and description. That means
we will learn about how to store persistent user data in our own Android application and get it back when
required. Also we will learn how to add, edit, retrieve (fetch), load, store, delete and update data in Android
SharedPr eferences. Android provides different options to save persistent application data. It is completely your
choices to which o ption you want to use for your application. Android provides below different data storage
options.
SharedPreferences
Store your ap plication’s pr ivate primitive data (working as key-value pairs).
You can use SharedPreferences to save any primitive data of your application like: boolean, float, int, long, and
string etc. This data will persist across user sessions (even if your application is closed or forcible killed by
Android OS).
SQLite Databases
Store your application’s structured data in your application’s private database. It will store in the application’s
context. I have already written a very nice article about how to save application’s data in your own Android
SQLite database. Click here to read this article.
Network Connection
http://techblogon.com/android-login-registration-screen-with-sqlite-database-example/http://techblogon.com/category/technologieshttp://techblogon.com/category/gadgetshttp://techblogon.com/https://twitter.com/techblogonhttp://www.facebook.com/Techblogonhttp://gplus.to/techblogonhttp://techblogon.com/?feed=rss2mailto:[email protected]://techblogon.com/privacy-policy/http://techblogon.com/contact-us/http://techblogon.com/about-us/mailto:[email protected]://gplus.to/techblogonhttp://www.facebook.com/Techblogonhttps://twitter.com/techblogonhttp://techblogon.com/android-login-registration-screen-with-sqlite-database-example/http://techblogon.com/category/tutorials/http://techblogon.com/category/tutorials/http://techblogon.com/android-login-registration-screen-with-sqlite-database-example/http://techblogon.com/http://techblogon.com/?feed=rss2http://techblogon.com/category/tutorials/android-tutorial/http://techblogon.com/category/internethttp://techblogon.com/http://techblogon.com/contact-us/http://techblogon.com/category/technologieshttp://techblogon.com/privacy-policy/http://techblogon.com/category/gadgets
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
2/15
Store your application’s 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 application’s 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. Let’s 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.
Simple Steps for Android Shared Preferences Use
http://techblogon.com/wp-content/uploads/2013/04/android-shared-preference-example.png
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
3/15
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.
Android SharedPreferences Initialization
Android SharedPreferences can be fetch using the function getSharedPreferences(). This function need a
context (your Activity context). so use your Activity context if you will call this from your activity class. If you cal
this from a non Activity class like Android services, then first store the context and use it
for getSharedPreferences(). Don’t worry we will discuss complete details in below example. this is only for the
code snippet. Finally we need an Android editor class to save the changes in the Android SharedPreferences.
Below is the code snippet.
First import the below package into your java file, where you want to use shared preference.
Storing Data into Android SharedPreferences
After the above initialization code, we need to follow the below code snippet for storing different types of data in
to Android SharedPreferences.
Note: In the above code snippet, to make the code buildable please change “float value”, “long value” to the
real float and long values.
Fetching Data from Android SharedPreferences
Data can be fetch from saved preferences by calling getString() (For string), getInt() (for Int) method etc. Note
that: these methods should be called using SharedPreferences not using Editor. Below is the code snippet.
1 import android.content.SharedPreferences;
12345
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - fo//here the first parameter is name of your pref file which will hold your data. you can give// Note here the 2nd parameter 0 is the default parameter for private access. Editor editor = pref.edit(); // used for save data
123456
7
editor.putBoolean("key_name1", true); // Storing boolean value - true or falseeditor.putString("key_name2", "string-value"); // Storing string valueeditor.putInt("key_name3", "int value"); // Storing integer valueeditor.putFloat("key_name4", "float value"); // Storing float valueeditor.putLong("key_name5", "long value"); // Storing long value
editor.commit(); // commit changes into sharedpreferences file.
http://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String,%20java.lang.String)
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
4/15
Deleting Data from Android SharedPreferences
If you want to delete some specific data from Android sharedpreferences, then we can call the
function remove(“key_name”) to delete that particular value. If you want to delete all the data, call clear()
function.
If you want to clear (delete) all data at a time then you can use the below code snippet.
Create Project: Android SharedPreferences Example
Now coming to the Android SharedPreferences Example. You can use the below example to learn about
Android Shared Preferences. We will get some input data (we have used 3 fields : Name, Employee ID and
Age) from user. Then we will save it into the shared preferences file, After that we will retrieve those values from
the android SharedPreferences file. To make the example very simple, we will use 2 buttons (Store and Load)for this purpose. Also i have implemented a Simple SharedPrefManager Class. which will perform all Android
SharedPreferences operations for you. You can use and edit this java file (SharedPrefManager Class) as per
your requirement. Only what you need to do is: replace the package name ‘ package
com.techblogon.sharedpreferenceexample;‘ to your application’s package name.
1. Create a project with project name: SharedPreferenceExample
2. Fill Application Name: SharedPreferenceExample
3. Fill Package Name as: package com.techblogon.sharedpreferenceexample;
4. I have used SDK version Android 4.0.3 and Eclipse Version Indigo. But you can use any version.
5. Add below xml file (activity_main.xml ) into your project’s res/layout folder. or you can copy the xml file
contents.
This the default xml file in the project. here we used 3 EditText field to get user data to store into the
sharedpreferences file. Also added 2 buttons (Store and Load) to make the operation simple.
1 SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - fo
1234567
// getting values from stored preferences// If any value is not present in the preferences file, then the second parameter will be thepref.getString("key_name1", ""); // getting Stringpref.getInt("key_name2", ""); // getting Integerpref.getFloat("key_name3", null); // getting Floatpref.getLong("key_name4", null); // getting Longpref.getBoolean("key_name5", true); // getting boolean
123
editor.remove("key_name1"); // will delete the key named key_name1editor.remove("key_name2"); // will delete key named key_name2editor.commit(); // commit above changes
12
editor.clear(); // clear all data.editor.commit(); // commit changes
1
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
5/15
234567891011
12131415161718192021222324252627282930313233343536
37383940414243444546474849
50515253545556575859606162
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity">
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
6/15
6. Add below Java file (SharedPrefManager.java) in you project’s /src folder.
This file contains a class ‘SharedPrefManager’, which will handle all Android SharedPreferences operations.
You just want to call those functions form where you want to store/load data in to the shared preference. All
functions are static in nature, so no need to create any instance of the class, just call these functions using the
class name with .dot operator. For example if you want to save data then just call
: SharedPrefManager.StoreToPref();
636465666768697071
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" /> >
12
3456789101112131415
16171819202122232425262728293031323334353637383940
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 onlypublic class SharedPrefManager { //this is your shared preference file name, in which we will save data public static final String MY_EMP_PREFS = "MySharedPref";
//saving the context, so that we can call all//shared pref methods from non activity classes.//because getSharedPreferences required the context.
//but in activity class we can call without this context private static Context mContext;
// 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;
public static void Init(Context context) { mContext = context; } public static void LoadFromPref() { SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0); // Note here the 2nd parameter 0 is the default parameter for private access, //Operating mode. Use 0 or MODE_PRIVATE for the default operation, mName = settings.getString("Name",""); // 1st parameter Name is the key an
mEid = settings.getString("EmpID",""); mAge = settings.getInt("Age",0); } public static void StoreToPref() { // get the existing preference file SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values SharedPreferences.Editor editor = settings.edit();
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
7/15
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
41424344454647484950
51525354555657585960616263646566676869707172737475
76777879808182838485868788
89909192
editor.putString("Name",mName); // Name is the key and mName is holding the value editor.putString("EmpID",mEid);// EmpID is the key and mEid is holding the value editor.putInt("Age", mAge); // Age is the key and mAge is holding the value
//final step to commit (save)the changes in to the shared pref editor.commit();
}
public static void DeleteSingleEntryFromPref(String keyName) {
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0); //need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit(); editor.remove(keyName); editor.commit(); }
public static void DeleteAllEntriesFromPref() { SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values SharedPreferences.Editor editor = settings.edit(); editor.clear(); editor.commit(); }
public static void SetName(String name) { mName =name; } public static void SetEmployeeID(String empID) { mEid = empID ; } public static void SetAge(int age)
{ mAge = age; }
public static String GetName() { return mName ; } public static String GetEmployeeID() { return mEid ; } public static int GetAge()
{ return mAge ; }}
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
8/15
and pass all user data to the SharedPrefManager class using it’s own functions, then we will store all data at a
time using SharedPrefManager class’s function SharedPrefManager.StoreToPref(). Similarly we will
use SharedPrefManager.LoadFromPref().
1234567891011121314151617
18192021222324252627282930
31323334353637383940414243
44454647484950515253545556
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; public class MainActivity extends Activity {
@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 function EditText editTextName,editTextEmpID,editTextAge; editTextName=(EditText)findViewById(R.id.editTextEnterName); editTextEmpID=(EditText)findViewById(R.id.editTextEnterEid); editTextAge=(EditText)findViewById(R.id.editTextEnterAge);
//convert EditText to string String srtTextName = editTextName.getText().toString(); String srtTextEmpID = editTextEmpID.getText().toString();
String strTextAge = editTextAge.getText().toString();
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 i if(0 != strTextAge.length()) SharedPrefManager.SetAge(Integer.parseInt(strTextAge)); // need integer value so con
//now save all to shared pref, all updated values are now available in SharedPrefManSharedPrefManager.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("");
Toast.makeText(this, "Data Successfully Stored to SharedPreference", Toast.LENGTH_LO
} public void onClickLoad(View v) {
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
9/15
8. Finally the Manifest File.
9. That’s it. Build and run the application on Android device/emulator.
57585960616263646566
676869707172737475767778798081828384
//Get all values from SharedPrefference file SharedPrefManager.LoadFromPref(); // all values are loaded into corresponding variab
//Now get the values form SharedPrefManager class using it's static functions. String strTextName,strTextEmpID; int iTextAge; strTextName = SharedPrefManager.GetName(); strTextEmpID = SharedPrefManager.GetEmployeeID(); iTextAge =SharedPrefManager.GetAge();
//Now we can show these persistent values on our activity (GUI) EditText tv = null; tv = (EditText)findViewById(R.id.editTextEnterName); tv.setText(strTextName); tv = (EditText)findViewById(R.id.editTextEnterEid); tv.setText(strTextEmpID); tv = (EditText)findViewById(R.id.editTextEnterAge); tv.setText(String.valueOf(iTextAge));
Toast.makeText(this, "Data Successfully Loaded from SharedPreference", Toast.LENGTH_ } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; }}
12345678910111213141516
1718192021222324252627
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
10/15
You can download Android SharedPreferences Example from here.
Tips on Android Shared Preference Uses
Sometimes you might want to delete the old SharedPreferences file. If you want to delete the old one and create
a new one, then you need to know the file location where this file is created for your application. Goto DDMS-
>File Explorer . Please refer to the below image.
Some Android SharedPreferences Issues and Solutions
Error: The new data overwrites the old data in Android Shared Preference
Solution: Android calls clear() function, when you save (commit) data. so all your existing data will be erased.
To prevent that, first you have to get all old data and save those in some variables, then add you new data and
save all at a time. You can use Android Vector and Android Array for this purpose.
Error: Data not saved in Android Shared Preference.
Solution: Sometimes the above issue happens with me also, there are several reasons. However delete the
preference file and create a new one might solve your problem. Make sure to save your date before delete.
http://techblogon.com/wp-content/uploads/2013/04/SharedPreferenceExample.ziphttps://plus.google.com/+Techblogon?prsrc=5https://twitter.com/intent/follow?original_referer=http%3A%2F%2Ftechblogon.com%2Fandroid-sharedpreferences-example-code%2F®ion=follow_link&screen_name=techblogon&tw_p=followbuttonhttp://techblogon.com/wp-content/uploads/2013/04/android-sharedpreference-file-location-in-device.jpghttps://twitter.com/intent/user?original_referer=http%3A%2F%2Ftechblogon.com%2Fandroid-sharedpreferences-example-code%2F®ion=count_link&screen_name=techblogon&tw_p=followbutton
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
11/15
Post By SmrutiRanjan (57 Posts)Working @ Samsung as a P roject Lead for AndroidSmartphones. I have been blogging since 2008.Previously I was w riting articles for other bloggers, butfinally I have started my own blog-"Techblogon".I am alsoan active contributor for the blog-"Gadgets n Gizmos
World". Job is my necessity, but blogging is my pass ion.
Website: → Techblogon
CONNECT
I hope this tutorial on Android SharedPreferences Example will help you at it’s best.
Previous Page
Android Tutorial Home Page
Next Page
android sharedpreferences between activities, android sharedpreferences editor , android sharedpreferences
tutorial, how to delete android shared preference file, how to use android shared preference, sharedpreferences
save issue
8 Responses to Android SharedPreferences Example Code(Save User Data)
1. Anil says:
April 15, 2013 at 6:10 am
Hi SmrutiRanjan,
I am regular reader of your android tutorial thanks for your tutorial and it’s 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/tag/android-sharedpreferences-between-activities/http://in.linkedin.com/pub/smruti-ranjan-nayak/62/ba9/52bhttp://techblogon.com/tag/android-sharedpreferences-tutorial/http://techblogon.com/android-sharedpreferences-example-code/?replytocom=474#respondhttp://techblogon.com/custom-toast-android-example-with-source-code-description/http://techblogon.com/tag/android-sharedpreferences-editor/https://plus.google.com/u/0/110318797292853934829/postshttp://techblogon.com/sample-code-listview-sqlite-database-connection-in-android/http://techblogon.com/http://twitter.com/twit2smrutihttp://techblogon.com/android-development-tutorial-for-beginners/http://www.facebook.com/smrutiranjantechieshttp://techblogon.com/author/smrutiranjan/http://techblogon.com/tag/sharedpreferences-save-issue/http://techblogon.com/http://techblogon.com/tag/how-to-delete-android-shared-preference-file/http://techblogon.com/android-sharedpreferences-example-code/?replytocom=467#respondhttp://techblogon.com/tag/how-to-use-android-shared-preference/http://techblogon.com/
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
12/15
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. Anil Yadav says:
May 7, 2013 at 7:27 am
Nice Tutorial Dear.
Can you post how fetch data in android using Json restful web services.
Because I search on google but not clear.
Thanks in advance.
Reply
3. Hemant katariya says:
May 9, 2013 at 5:24 am
Hello Sir, Thank you for posting these tutorial.
Can you help me related to some sample.
So please upload google map v2 and twitter or facebook tutorial or send me samples. Urgently require
Reply
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/http://techblogon.com/android-sharedpreferences-example-code/?replytocom=478#respondhttp://techblogon.com/android-sharedpreferences-example-code/?replytocom=625#respondhttp://techblogon.com/android-sharedpreferences-example-code/?replytocom=649#respondhttp://techblogon.com/android-sharedpreferences-example-code/?replytocom=990#respondhttp://techblogon.com/android-sharedpreferences-example-code/?replytocom=986#respond
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
13/15
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:
Post Comment
http://techblogon.com/android-sharedpreferences-example-code/?replytocom=1511#respond
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
14/15
RSS Feed Google Plus
Search
1,859 people like this. Be the first of your friends.Like
12
Follow @techblogon 216 follow ers
Enter your Email Address...
Subscribe
Archives
March 2015
July 2014
April 2014
October 2013
August 2013
July 2013
June 2013
May 2013
April 2013
March 2013
February 2013
January 2013December 2012
Categories
Android
Android Tutorial
Design Patterns
Displays
E-Commerce
Techblogon
+ 305
Follow +1
Recommend on Google
http://techblogon.com/category/tutorials/android-tutorial/http://feeds.feedburner.com/techblogonhttp://techblogon.com/2014/04/http://techblogon.com/2013/03/http://techblogon.com/2013/10/http://plus.google.com/110318797292853934829http://techblogon.com/2015/03/http://techblogon.com/2013/05/http://techblogon.com/2013/08/http://techblogon.com/2014/07/http://techblogon.com/2013/07/http://techblogon.com/2013/01/http://techblogon.com/category/gadgets/displays/http://techblogon.com/category/tutorials/android-tutorial/http://techblogon.com/category/technologies/e-commerce/http://techblogon.com/2013/06/http://techblogon.com/2013/02/http://techblogon.com/category/tutorials/design-patterns/http://techblogon.com/category/technologies/android/http://techblogon.com/2013/04/http://techblogon.com/2012/12/
8/18/2019 Android SharedPreferences Example Code(Save User Data) _ Techblogon
15/15
Gadgets
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/wp-login.phphttp://techblogon.com/comments/feed/http://techblogon.com/privacy-policy/http://techblogon.com/category/technologies/http://techblogon.com/category/gadgets/mobile-phones/https://wordpress.org/http://techblogon.com/category/tutorials/http://techblogon.com/http://techblogon.com/feed/http://techblogon.com/category/technologies/softwares/http://techblogon.com/category/technologies/windows/http://techblogon.com/about-us/http://techblogon.com/contact-us/http://techblogon.com/category/gadgets/http://techblogon.com/category/internet/google/http://techblogon.com/category/internet/