Android SharedPreferences Example Code.docx
《Android SharedPreferences Example Code.docx》由会员分享,可在线阅读,更多相关《Android SharedPreferences Example Code.docx(36页珍藏版)》请在冰豆网上搜索。
AndroidSharedPreferencesExampleCode
AndroidSharedPreferencesExampleCode(SaveUserData)
Simple AndroidSharedPreferencesExamplewithCodeDescription
HerewewilldiscussaboutAndroidSharedPreferencesexamplewithsourcecodeanddescription.ThatmeanswewilllearnabouthowtostorepersistentuserdatainourownAndroidapplicationandgetitbackwhenrequired.Alsowewilllearnhowtoadd,edit,retrieve(fetch),load,store,deleteandupdatedatainAndroidSharedPreferences.Androidprovidesdifferentoptionstosavepersistentapplicationdata.Itiscompletelyyourchoicestowhichoptionyouwanttouseforyourapplication.Androidprovidesbelowdifferentdatastorageoptions.
SharedPreferences
Storeyourapplication’sprivateprimitivedata(workingaskey-valuepairs).
YoucanuseSharedPreferencestosaveanyprimitivedataofyourapplicationlike:
boolean,float,int,long,andstringetc.Thisdatawillpersistacrossusersessions(evenifyourapplicationisclosedorforciblekilledbyAndroidOS).
SQLiteDatabases
Storeyourapplication’sstructureddatainyourapplication’sprivatedatabase.Itwillstoreintheapplication’scontext.Ihavealreadywrittenaverynicearticleabouthowtosaveapplication’sdatainyourownAndroidSQLitedatabase.Clickheretoreadthisarticle.
NetworkConnection
Storeyourapplication’sdataonthewebwithyourownnetworkserver.Sothatotheruserscanaccessitwhenrequired.
InternalStorage
Storeyourapplicationsprivatedataonthephonememory(devicememory)
ExternalStorage
Storeyourapplication’sdataonthesharedexternalstorage,sothatotherapplicationcanbeaccessitifrequired.
NowitisenoughforsomebasicideaaboutdatastoringinAndroid.Let’scometoourmainfocuse.g. “AndroidSharedPreferencesexamplewithsourcecodedescription”
TomakethisAndroidsharedpreferenceexampleverysimple,wewillusedifferentAndroidprimitivedatatypeslike:
boolean,float,int,long,andstringetc andstoresomeuserdataintoAndroidSharedPreference. Thenwewillretrieve(fetch)thosestoreddatafromAndroidSharedPreferences.
Note:
Android SharedPreferencesusesonlyKey-Valuepairforstoringdata,thatmeans,whenwewillstoredatatoAndroidSharedPreferences,wewilluseauniquekeyandsomecorrospondingdatawiththatkey.
SimpleStepsfor AndroidSharedPreferencesUse
Step1:
Createanew SharedPreferencesfileinyourAndroidapplication.Wewillopenitifitisalreadyexist.WewillusethefunctiongetSharedPreferences() functionfromtheinbuilt Androidclass.
Step2:
Forgettingdatafromthe AndroidSharedPreferencesfile,wewillusefunctionslike getString(),getInt()etc.
Step3:
Forstoringthedata,weneedtousetheAndroidEditorClassSharedPreferences.Editor.Thenwewill storedataintothe AndroidSharedPreferencesfileusingfunctions putString(),putInt()etc.thencommitthewholedatausingcommit()function.
AndroidSharedPreferences Initialization
AndroidSharedPreferencescanbefetchusingthefunction getSharedPreferences(). Thisfunctionneedacontext(yourActivitycontext).souseyourActivitycontextifyouwillcallthisfromyouractivityclass.IfyoucallthisfromanonActivityclasslikeAndroidservices,thenfirststorethecontextanduseitfor getSharedPreferences().Don’tworrywewilldiscusscompletedetailsinbelowexample.thisisonlyforthecodesnippet.FinallyweneedanAndroideditorclasstosavethechangesintheAndroidSharedPreferences.Belowisthecodesnippet.
Firstimportthebelowpackageintoyourjavafile,whereyouwanttousesharedpreference.
1
importandroid.content.SharedPreferences;
SharedPreferencespref=getApplicationContext().getSharedPreferences("MyPref",0);//0-forprivatemode
//herethefirstparameterisnameofyourpreffilewhichwillholdyourdata.youcangiveanyname.
//Noteherethe2ndparameter0isthedefaultparameterforprivateaccess.
Editoreditor=pref.edit();//usedforsavedata
StoringDatainto AndroidSharedPreferences
Aftertheaboveinitializationcode,weneedtofollowthebelowcodesnippetforstoringdifferenttypesofdataintoAndroidSharedPreferences.
editor.putBoolean("key_name1",true);//Storingbooleanvalue-trueorfalse
editor.putString("key_name2","string-value");//Storingstringvalue
editor.putInt("key_name3","intvalue");//Storingintegervalue
editor.putFloat("key_name4","floatvalue");//Storingfloatvalue
editor.putLong("key_name5","longvalue");//Storinglongvalue
mit();//commitchangesintosharedpreferencesfile.
Note:
Intheabovecodesnippet,tomakethecodebuildablepleasechange ”floatvalue”,“longvalue”totherealfloatandlongvalues.
FetchingDatafrom AndroidSharedPreferences
Datacanbefetchfromsavedpreferencesbycalling getString() (Forstring),getInt()(forInt) methodetc.Notethat:
thesemethodsshouldbecalledusingSharedPreferencesnotusingEditor.Belowisthecodesnippet.
1
SharedPreferencespref=getApplicationContext().getSharedPreferences("MyPref",0);//0-forprivatemode
//gettingvaluesfromstoredpreferences
//Ifanyvalueisnotpresentinthepreferencesfile,thenthesecondparameterwillbethedefaultvalue-//Inthiscasenull
pref.getString("key_name1","");//gettingString
pref.getInt("key_name2","");//gettingInteger
pref.getFloat("key_name3",null);//gettingFloat
pref.getLong("key_name4",null);//gettingLong
pref.getBoolean("key_name5",true);//gettingboolean
DeletingDatafrom AndroidSharedPreferences
IfyouwanttodeletesomespecificdatafromAndroidsharedpreferences,thenwecancallthefunction remove(“key_name”) todeletethatparticularvalue.Ifyouwanttodeleteallthedata,call clear()function.
editor.remove("key_name1");//willdeletethekeynamedkey_name1
editor.remove("key_name2");//willdeletekeynamedkey_name2
mit();//commitabovechanges
Ifyouwanttoclear(delete)alldataatatimethenyoucanusethebelowcodesnippet.
editor.clear();//clearalldata.
mit();//commitchanges
CreateProject:
AndroidSharedPreferencesExample
NowcomingtotheAndroidSharedPreferencesExample.YoucanusethebelowexampletolearnaboutAndroidSharedPreferences.Wewillgetsomeinputdata(wehaveused3fields:
Name,EmployeeIDandAge)fromuser.Thenwewillsaveitintothesharedpreferencesfile,AfterthatwewillretrievethosevaluesfromtheandroidSharedPreferencesfile.Tomaketheexampleverysimple,wewilluse2buttons(Store andLoad)forthispurpose.AlsoihaveimplementedaSimple SharedPrefManagerClass.whichwillperformallAndroidSharedPreferencesoperationsforyou.Youcanuseandeditthisjavafile(SharedPrefManager Class)asperyourrequirement.Onlywhatyouneedtodois:
replacethepackagename‘packagecom.techblogon.sharedpreferenceexample;‘toyourapplication’spackagename.
1.Createaprojectwithprojectname:
SharedPreferenceExample
2.FillApplicationName:
SharedPreferenceExample
3.FillPackageNameas:
packagecom.techblogon.sharedpreferenceexample;
4.IhaveusedSDKversion Android4.0.3 andEclipseVersion Indigo.Butyoucanuseanyversion.
5.Addbelowxmlfile(activity_main.xml)into yourproject’s res/layout folder.oryoucancopythexmlfilecontents.
Thisthedefaultxmlfileintheproject.hereweused3EditTextfieldtogetuserdatatostoreintothesharedpreferencesfile.Alsoadded2buttons(StoreandLoad)tomaketheoperationsimple.
android="
xmlns:
tools="
android:
layout_width="match_parent"
android:
layout_height="match_parent"
android:
orientation="vertical"
tools:
context=".MainActivity">
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="SharedPreferenceExample"
android:
ems="10">
android:
id="@+id/editTextEnterName"
android:
layout_width="fill_parent"
android:
layout_height="wrap_content"
android:
layout_marginTop="10dp"
android:
maxLength="30"
android:
hint="EnterYourName">
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="EnterYourEmployeeID">
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="EnterYourAge">
android="
xmlns:
tools="
android:
layout_width="match_parent"
android:
layout_height="match_parent"
android:
orientation="horizontal"
android:
layout_marginTop="10dp"
android:
gravity="center_horizontal">