Você está na página 1de 10

3/23/2015

AndroidSharedPreferencesTutorial

ANDROIDSHAREDPREFERENCESTUTORIAL
http://www.tutorialspoint.com/android/android_shared_preferences.htm

Copyrighttutorialspoint.com

Androidprovidesmanywaysofstoringdataofanapplication.OneofthiswayiscalledSharedPreferences.SharedPreferencesallow
youtosaveandretrievedataintheformofkey,valuepair.
Inordertousesharedpreferences,youhavetocallamethodgetSharedPreferencesthatreturnsaSharedPreferenceinstancepoiting
tothefilethatcontainsthevaluesofpreferences.
SharedPreferencessharedpreferences=getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);

ThefirstparameteristhekeyandthesecondparameteristheMODE.Apartfromprivatethereareothermodesavailaiblethatare
listedbelow:

Sr.NO

Modeanddescription

MODE_APPEND
Thiswillappendthenewpreferenceswiththealreadyexisitingpreferences

MODE_ENABLE_WRITE_AHEAD_LOGGING
Databaseopenflag.Whenitisset,itwouldenablewriteaheadloggingbydefault

MODE_MULTI_PROCESS
Thismethodwillcheckformodificationofpreferencesevenifthesharedpreferenceinstancehasalreadybeenloaded

MODE_PRIVATE
Bysettingthismode,thefilecanonlybeaccessedusingcallingapplication

MODE_WORLD_READABLE
Thismodeallowotherapplicationtoreadthepreferences

MODE_WORLD_WRITEABLE
Thismodeallowotherapplicationtowritethepreferences

YoucansavesomethinginthesharedpreferencesbyusingSharedPreferences.Editorclass.Youwillcalltheeditmethodof
SharedPreferenceinstanceandwillrecieveitinaneditorobject.Itssyntaxis:
Editoreditor=sharedpreferences.edit();
editor.putString("key","value");
editor.commit();

ApartfromtheputStringmethod,therearemethodsavailaibleintheeditorclassthatallowsmanipulationofdatainsideshared
preferences.Theyarelistedasfollows:

Sr.NO

Modeanddescription

apply
Itisanabstractmethod.ItwillcommityourchangesbackfromeditortothesharedPreferenceobjectyouarecalling

clear
Itwillremoveallvaluesfromtheeditor

removeS tringkey
Itwillremovethevaluewhosekeyhasbeenpassedasaparameter

putLongS tringkey, longvalue


Itwillsavealongvalueinapreferenceeditor

http://www.tutorialspoint.com/cgibin/printpage.cgi

1/10

3/23/2015

AndroidSharedPreferencesTutorial

putInt S tringkey, intvalue


Itwillsaveaintegervalueinapreferenceeditor

putFloat S tringkey, f loatvalue


Itwillsaveafloatvalueinapreferenceeditor

Example
ThisexampledemonstratestheuseoftheSharedPreferences.Itdisplayascreenwithsometextfields,whosevaluearesavedwhen
theapplicationisclosedandbroughtbackwhenitisopenedagain.
Toexperimentwiththisexample,youneedtorunthisonanactualdeviceonafterdevelopingtheapplicationaccordingtothesteps
below:

Steps

Description

YouwilluseEclipseIDEtocreateanAndroidapplicationandnameitasSharedPreferencesunderapackage
com.example.sharedpreferences.Whilecreatingthisproject,makesureyouTargetSDKandCompileWithatthelatest
versionofAndroidSDKtousehigherlevelsofAPIs.

Modifysrc/MainActivity.javafiletoaddprogresscodetodisplaythespinningprogressdialog.

Modifyres/layout/activity_main.xmlfiletoaddrespectiveXMLcode.

Modifyres/values/string.xmlfiletoaddamessageasastringconstant.

Runtheapplicationandchoosearunningandroiddeviceandinstalltheapplicationonitandverifytheresults.

Followingisthecontentofthemodifiedmainactivityfilesrc/com.example.sharedpreferences/MainActivity.java.
packagecom.example.sharedpreferences;
importcom.example.sharedpreferences.*;
importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.content.Context;
importandroid.content.SharedPreferences;
importandroid.content.SharedPreferences.Editor;
importandroid.view.Menu;
importandroid.view.View;
importandroid.widget.TextView;
publicclassMainActivityextendsActivity{
TextViewname;
TextViewphone;
TextViewemail;
TextViewstreet;
TextViewplace;
publicstaticfinalStringMyPREFERENCES="MyPrefs";
publicstaticfinalStringName="nameKey";
publicstaticfinalStringPhone="phoneKey";
publicstaticfinalStringEmail="emailKey";
publicstaticfinalStringStreet="streetKey";
publicstaticfinalStringPlace="placeKey";
SharedPreferencessharedpreferences;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);

http://www.tutorialspoint.com/cgibin/printpage.cgi

2/10

3/23/2015

AndroidSharedPreferencesTutorial

setContentView(R.layout.activity_main);
name=(TextView)findViewById(R.id.editTextName);
phone=(TextView)findViewById(R.id.editTextPhone);
email=(TextView)findViewById(R.id.editTextStreet);
street=(TextView)findViewById(R.id.editTextEmail);
place=(TextView)findViewById(R.id.editTextCity);
sharedpreferences=getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
if(sharedpreferences.contains(Name))
{
name.setText(sharedpreferences.getString(Name,""));
}
if(sharedpreferences.contains(Phone))
{
phone.setText(sharedpreferences.getString(Phone,""));
}
if(sharedpreferences.contains(Email))
{
email.setText(sharedpreferences.getString(Email,""));
}
if(sharedpreferences.contains(Street))
{
street.setText(sharedpreferences.getString(Street,""));
}
if(sharedpreferences.contains(Place))
{
place.setText(sharedpreferences.getString(Place,""));
}
}
publicvoidrun(Viewview){
Stringn=name.getText().toString();
Stringph=phone.getText().toString();
Stringe=email.getText().toString();
Strings=street.getText().toString();
Stringp=place.getText().toString();
Editoreditor=sharedpreferences.edit();
editor.putString(Name,n);
editor.putString(Phone,ph);
editor.putString(Email,e);
editor.putString(Street,s);
editor.putString(Place,p);
editor.commit();
}
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
}

Followingisthecontentofthemodifiedmainactivityfileres/layout/activiy_main.xml.
<ScrollViewxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"

http://www.tutorialspoint.com/cgibin/printpage.cgi

3/10

3/23/2015

AndroidSharedPreferencesTutorial

tools:context=".DisplayContact">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>
<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text">
</EditText>
<EditText
android:id="@+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextStreet"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress"/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextName"
android:layout_alignParentLeft="true"
android:text="@string/name"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="@string/save"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView1"
android:text="@string/email"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextPhone"
android:layout_alignLeft="@+id/textView1"
android:text="@string/phone"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="@+id/textView4"

http://www.tutorialspoint.com/cgibin/printpage.cgi

4/10

3/23/2015

AndroidSharedPreferencesTutorial

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView5"
android:text="@string/street"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<EditText
android:id="@+id/editTextCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editTextName"
android:layout_below="@+id/editTextEmail"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="text"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editTextCity"
android:layout_alignBottom="@+id/editTextCity"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/editTextEmail"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<EditText
android:id="@+id/editTextStreet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextName"
android:layout_below="@+id/editTextPhone"
android:ems="10"
android:inputType="text">
<requestFocus/>
</EditText>
<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextName"
android:ems="10"
android:inputType="phone|text"/>
</RelativeLayout>
</ScrollView>

Followingisthecontentofthemodifiedcontentoffileres/values/strings.xml.
<?xmlversion="1.0"encoding="utf8"?>
<resources>
<stringname="app_name">SharedPreferences</string>
<stringname="action_settings">Settings</string>
<stringname="hello_world">Helloworld!</string>
<stringname="name">Name</string>
<stringname="phone">Phone</string>
<stringname="email">Email</string>
<stringname="street">Street</string>
<stringname="country">City/State/Zip</string>
<stringname="save">SaveContact</string>

http://www.tutorialspoint.com/cgibin/printpage.cgi

5/10

3/23/2015

AndroidSharedPreferencesTutorial

</resources>

FollowingisthecontentdefaultfileAndroidManifest.xml.
<?xmlversion="1.0"encoding="utf8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sharedpreferences"
android:versionCode="1"
android:versionName="1.0">
<usessdk
android:minSdkVersion="8"
android:targetSdkVersion="17"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.example.sharedpreferences.MainActivity"
android:label="@string/app_name">
<intentfilter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intentfilter>
</activity>
</application>
</manifest>

Let'strytorunyourSharedPreferencesapplication.IassumeyouhaveconnectedyouractualAndroidMobiledevicewithyour
computer.ToruntheappfromEclipse,openoneofyourproject'sactivityfilesandclickRun
iconfromthetoolbar.Before
startingyourapplication,EclipsewilldisplayfollowingwindowtoselectanoptionwhereyouwanttorunyourAndroidapplication.

http://www.tutorialspoint.com/cgibin/printpage.cgi

6/10

3/23/2015

AndroidSharedPreferencesTutorial

Selectyourmobiledeviceasanoptionandthencheckyourmobiledevicewhichwilldisplayfollowingscreen:

http://www.tutorialspoint.com/cgibin/printpage.cgi

7/10

3/23/2015

AndroidSharedPreferencesTutorial

Nowjustputinsometextinthefield.Likeiputsomerandomnameandotherinformationandclickonsavebutton.

http://www.tutorialspoint.com/cgibin/printpage.cgi

8/10

3/23/2015

AndroidSharedPreferencesTutorial

Nowwhenyoupresssavebutton,thetextwillbesavedinthesharedpreferences.Nowpressbackbuttonandexittheapplication.
Nowopenitagainandyouwillseeallthetextyouhavewrittenbackinyourapplication.

http://www.tutorialspoint.com/cgibin/printpage.cgi

9/10

3/23/2015

http://www.tutorialspoint.com/cgibin/printpage.cgi

AndroidSharedPreferencesTutorial

10/10

Você também pode gostar