Sie sind auf Seite 1von 29

Android

Persistency: Preferences


14
Victor Matos
Cleveland State University

Notes are based on:
The Busy Coder's Guide to Android Development
by Mark L. Murphy
Copyright 2008-2009 CommonsWare, LLC.
ISBN: 978-0-9816780-0-9
&
Android Developers
http://developer.android.com/index.html
2
14. Android Preferences

Android Data Storage

2
Android provides several options for you to save persistent application data. The
solution you choose depends on your specific needs: private/public, small/large
datasets.

Your data storage options are the following:

Shared Preferences Store private primitive data in key-value pairs.
Internal Storage Store private data on the device memory.
External Storage Store public data on the shared external storage.
SQLite Databases Store structured data in a private database.
Network Connection Store data on the web with your own network server.
Content Provider Shared repository globally shared by all apps.


http://developer.android.com/guide/topics/data/data-storage.html
3
14. Android Preferences

Android Data Storage

3

Android uses a particular data sharing
scheme:

On Android, all application data
held in the devices private memory
area is private to that application

Note:
Private memory usually small and different from
external storage (SDcards).

http://developer.android.com/guide/topics/data/data-storage.html
4
14. Android Preferences

Android Data Storage

4
On Android, all
application data
(including files)
are private to
that application.

http://developer.android.com/guide/topics/data/data-storage.html
5
14. Android Preferences

Android Data Storage

5
Content Providers provide a data-layer for non-Sql developers (to
be discussed later)

Android uses content providers for global data objects, such as
image,
audio,
video files and
personal contact information.




6
14. Android Preferences

Preferences

6


Preferences is an Android lightweight mechanism to store and retrieve
<key-value> pairs of primitive data types (also called Maps, and
Associative Arrays.

PREFERENCES are typically used to keep state information
and shared data among several activities of an application.


In each entry of the form <key-value> the key is a string
and the value must be a primitive data type.


Preferences are similar to Bundles however
they are persistent while Bundles are not.
7
14. Android Preferences

Preferences

7


Using Preferences API calls
You have three API choices to pick a Preference:

1. getPreferences() from within your Activity, to access activity
specific preferences

2. getSharedPreferences() from within your Activity to access
application-level preferences

3. getDefaultSharedPreferences(), on PreferencesManager, to
get the shared preferences that work in concert with
Android's overall preference framework
8
14. Android Preferences

Preferences

8


Using Preferences API calls
All of the getXXX Preference methods return a Preference object whose
contents can be manipulated by an editor that allows putXxx and getXxx
commands to place data in and out of the Preference container.

Xxx = { Long, Int, Double, Boolean, String }
Preference
Container
Key Value
E
D
I
T
O
R

.getXxx(key
n
)
.getAll()
.getStringSet()

.putXxx(key
n
, value
n
)
.remove(key
n
)
.clear()
.commit()
9
14. Android Preferences

Preferences

9


Example1
1. In this example a persistent SharedPreferences object is created at the end
of an activity lifecycle. It contains some formatting specifications made by
the user to define aspects of the graphical interface.

2. When re-executed, it finds the saved Preference and uses its persistent data
to reproduce the UI according to the specifications previously given by the
user.
Warning
Make sure you test from a fresh configuration. If necessary use DDMS
and delete existing Preferences held in the applications name-space.
10
14. Android Preferences

Preferences

10


Example1
Warning
Make sure you test from a fresh configuration. Next images illustrate the process of
removing existing traces of an application from the phones system area using devices
Application Manager
Menu
Button
11
14. Android Preferences

Preferences

11


Example1. cont.
Warning
Make sure you test from a fresh configuration. Next images illustrate the process of
removing existing traces of an application from the phones system area using devices
Application Manager
12 12
14. Android Preferences

Preferences

12


Example1: Saving/Retrieving a SharedPreference Object holding UI user choices.
Initial UI with no choices
made/save yet.
Images of the choices made by the user regarding the
looks of the UI. The green screen corresponds to the
fancy layout, the grey screen is the simple choice.
Data is saved into the SharedPreference object:
myPreferences_001.
13 13
14. Android Preferences

Preferences

13
Example1: Saving/Retrieving a SharedPreference Object
Using DDMS to explore the Devices memory map.
Observe the choices made by the user are saved in
the data/data/Shared_prefs/ folder as an XML file.
Image of the preference file
(obtained by pulling a copy of
the file out of the device).
<?xml ver si on="1.0" encoding="utf-8"?>
<Li near Layout
andr oi d: i d="@+id/linLayout1Vertical"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="fill_parent"
andr oi d: or i ent at i on="vertical"
xml ns: andr oi d="http://schemas.android.com/apk/res/android" >

<Li near Layout
andr oi d: i d="@+id/linLayout2Horizontal"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content >
<But t on
andr oi d: i d="@+id/btnPrefSimple"
andr oi d: l ayout _wi dt h="wrap_content"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: t ext ="Pref Simple UI / >
<But t on
andr oi d: i d="@+id/btnPrefFancy"
andr oi d: l ayout _wi dt h="wrap_content"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: t ext ="Pref Fancy UI / >
</ Li near Layout >

<Text Vi ew
andr oi d: i d="@+id/txtCaption1"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: backgr ound="#ff006666"
andr oi d: t ext ="This is some sample text / >

</ Li near Layout >
14 14
14. Android Preferences

Preferences

14


Example1: Saving/Retrieving a SharedPreference Object
15 15
14. Android Preferences

Preferences

15


Example1: Saving/Retrieving a SharedPreference Object
package cis493.preferences;
import ...

public class PreferenceDemo0 extends Activity implements OnClickListener {
But t on bt nSi mpl ePr ef ;
But t on bt nFancyPr ef ;
Text Vi ew t xt Capt i on1;
Bool ean f ancyPr ef Chosen = false;
Vi ew myLayout 1Ver t i cal ;

final int mode = Activity.MODE_PRIVATE;
final String MYPREFS = "MyPreferences_001";

/ / cr eat e a r ef er ence t o t he shar ed pr ef er ences obj ect
Shar edPr ef er ences myShar edPr ef er ences;

/ / obt ai n an edi t or t o add dat a t o my Shar edPr ef er ences obj ect
Shar edPr ef er ences. Edi t or myEdi t or ;

File creation modes:
MODE_APPEND
MODE_
16 16
14. Android Preferences

Preferences

16


Example1: Saving/Retrieving a SharedPreference Object
@Over r i de
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
set Cont ent Vi ew( R. l ayout . main);
myLayout 1Ver t i cal = ( Vi ew) f i ndVi ewByI d( R. i d. linLayout1Vertical);
t xt Capt i on1 = ( Text Vi ew) f i ndVi ewByI d( R. i d. txtCaption1);
t xt Capt i on1. set Text ( "Thi s i s a sampl e l i ne \ n
+ "suggest i ng t he way t he UI l ooks \ n"
+ "af t er you choose your pr ef er ence") ;
/ / cr eat e a r ef er ence & edi t or f or t he shar ed pr ef er ences obj ect
myShar edPr ef er ences = get Shar edPr ef er ences( MYPREFS, 0) ;
myEdi t or = myShar edPr ef er ences. edi t ( ) ;
/ / has a Pr ef er ences f i l e been al r eady cr eat ed?
if (mySharedPreferences != null
&& myShar edPr ef er ences. cont ai ns( "backCol or " ) ) {
/ / obj ect and key f ound, show al l saved val ues
appl ySavedPr ef er ences( ) ;
} else {
Toast . makeText(getApplicationContext(),
"No Pr ef er ences f ound", 1) . show( ) ;
}
bt nSi mpl ePr ef = ( But t on) f i ndVi ewByI d( R. i d. btnPrefSimple);
bt nSi mpl ePr ef . set OnCl i ckLi st ener ( this);
bt nFancyPr ef = ( But t on) f i ndVi ewByI d( R. i d. btnPrefFancy);
bt nFancyPr ef . set OnCl i ckLi st ener ( this);
}/ / onCr eat e
17 17
14. Android Preferences

Preferences

17


Example1: Saving/Retrieving a SharedPreference Object
@Over r i de
public void onClick(View v) {
/ / cl ear al l pr evi ous sel ect i ons
myEdi t or . cl ear ( ) ;

/ / what but t on has been cl i cked?
if (v.getId() == btnSimplePref.getId()) {
myEdi t or . put I nt ( "backCol or ", Col or . BLACK);// black background
myEdi t or . put I nt ( "t ext Si ze" , 12) ; / / humbl e smal l f ont
} else { // case btnFancyPref
myEdi t or . put I nt ( "backCol or ", Col or . BLUE); // fancy blue
myEdi t or . put I nt ( "t ext Si ze" , 20) ; / / f ancy bi g
myEdi t or . put St r i ng( "t ext St yl e" , " bol d") ; / / f ancy bol d
myEdi t or . put I nt ( "l ayout Col or " , Col or . GREEN);//fancy green
}
myEdi t or . commi t ( ) ;
appl ySavedPr ef er ences( ) ;
}

18 18
14. Android Preferences

Preferences

18


Example1: Saving/Retrieving a SharedPreference Object
@Over r i de
protected void onPause() {
/ / war ni ng: act i vi t y i s on i t s l ast st at e of vi si bi l i t y! .
/ / I t ' s on t he edge of bei ng ki l l ed! Bet t er save al l cur r ent
/ / st at e dat a i nt o Pr ef er ence obj ect ( be qui ck! )
myEdi t or . put St r i ng( "Dat eLast Execut i on", new Date().toLocaleString());
myEdi t or . commi t ( ) ;
super.onPause();
}

19 19
14. Android Preferences

Preferences

19


Example1: Saving/Retrieving a SharedPreference Object
public void applySavedPreferences() {
/ / ext r act t he <key/ val ue> pai r s, use def aul t par amf or mi ssi ng dat a
int backColor = mySharedPreferences.getInt("backColor",Color.BLACK);
int textSize = mySharedPreferences.getInt("textSize", 12);
St r i ng t ext St yl e = mySharedPreferences.getString("textStyle", "normal");
int layoutColor = mySharedPreferences.getInt("layoutColor",Color.DKGRAY);
St r i ng msg = "col or " + backCol or + " \ n"
+ "si ze " + t ext Si ze + " \ n"
+ "st yl e " + t ext St yl e;
Toast . makeText(getApplicationContext(), msg, 1).show();

t xt Capt i on1. set Backgr oundCol or ( backCol or ) ;
t xt Capt i on1. set Text Si ze( t ext Si ze) ;
if (textStyle.compareTo("normal")==0){
t xt Capt i on1. set Typef ace( Typef ace. SERIF,Typeface.NORMAL);
}
else {
t xt Capt i on1. set Typef ace( Typef ace. SERIF,Typeface.BOLD);
}
myLayout 1Ver t i cal . set Backgr oundCol or ( l ayout Col or ) ;
}/ / appl ySavedPr ef er ences

}/ / cl ass
20 20
14. Android Preferences

Preferences

20


Example2
1. In this example a persistent SharedPreferences object is created at the end
of an activity lifecycle. It contains data (name, phone, credit, etc. of a
fictional customer)

2. The process is interrupted using the Back Button and re-executed later.

3. Just before been killed, the state of the running application is saved in the
designated Preference object.

4. When re-executed, it finds the saved Preference and uses its persistent data.
Warning
Make sure you test from a fresh configuration. If necessary use DDMS
and delete existing Preferences held in the applications name-space.
21
14. Android Preferences

Preferences

21


Example2: Saving/Retrieving a SharedPreference Object containing business data.
Image of the data held in the
SharedPreferences object
displayed the first time the Activity
Preferences1 is executed.
Image of the saved Preference data
displayed the second time the
Activity Preferences1 is executed.
22
14. Android Preferences

Preferences

22


Example2: Saving/Retrieving a SharedPreference Object
Use DDMS to
see persistent
data set

23
14. Android Preferences

Preferences

23


Example2: Saving/Retrieving a SharedPreference Object
Persistent data is saved in
the phones memory as an
XML file. This image was
pulled from the device
using DDMS.
24
14. Android Preferences

Preferences

24


Example2: Saving/Retrieving a SharedPreference Object
<?xml ver si on="1.0" encoding="utf-8"?>
<Li near Layout
andr oi d: i d="@+id/linLayou1"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="fill_parent"
andr oi d: backgr ound="#ff0000ff"
andr oi d: or i ent at i on="vertical"
xml ns: andr oi d="http://schemas.android.com/apk/res/android"
>
<Text Vi ew
andr oi d: i d="@+id/captionBox"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: t ext ="SharedPreferences Container: Customer Data"
andr oi d: l ayout _mar gi n="5px" android:textStyle="bold">
</ Text Vi ew>
<Edi t Text
andr oi d: i d="@+id/txtPref"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: l ayout _mar gi n="10px"
>
</ Edi t Text >
</ Li near Layout >
25
14. Android Preferences

Preferences

25


Example2: Saving/Retrieving a SharedPreference Object
package cis493.preferences;

import java.util.Date;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.*;

public class Preference1 extends Activity {
public static final String MYPREFS = "MySharedPreferences001";
/ / t hi s dat a val ues descr i be a t ypi cal cust omer r ecor d
St r i ng cust Name = " n. a. ";
int custAge = 0;
float custCredit = 0;
long custNumber = 0;
St r i ng cust Dat eLast Cal l ;

Text Vi ew capt i onBox;
Edi t Text t xt Pr ef ;
final int mode = Activity.MODE_PRIVATE;
26
14. Android Preferences

Preferences

26


Example2: Saving/Retrieving a SharedPreference Object
@Over r i de
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
set Cont ent Vi ew( R. l ayout . main);
t xt Pr ef = ( Edi t Text ) f i ndVi ewByI d( R. i d. txtPref);
capt i onBox = ( Text Vi ew) f i ndVi ewByI d( R. i d. captionBox);
capt i onBox. set Text ( "Shar edPr ef er ence Cont ai ner : \ n\ n"+
"we ar e wor ki ng on cust omer Macar ena \ n" +
"f ake an i nt er r upt i on, pr ess ' Back But t on' \ n" +
"r e- execut e t he appl i cat i on. ") ;

/ / cr eat e a r ef er ence t o t he shar ed pr ef er ences obj ect
int mode = Activity.MODE_PRIVATE;
Shar edPr ef er ences myShar edPr ef er ences = get Shar edPr ef er ences( MYPREFS, mode);
/ / i s t her e an exi st i ng Pr ef er ences f r ompr evi ous execut i ons of t hi s app?
if (mySharedPreferences != null &&
mySharedPreferences.contains("custName")) {
/ / obj ect and key f ound, show al l saved val ues
showSavedPr ef er ences( ) ;
}
else
{
t xt Pr ef . set Text ( "nada") ;
}
}/ / onCr eat e
27
14. Android Preferences

Preferences

27


Example2: Saving/Retrieving a SharedPreference Object
@Over r i de
protected void onPause() {
/ / war ni ng: act i vi t y i s on l ast st at e of vi si bi l i t y! We ar e on t he
/ / edge of been ki l l ed! Bet t er save cur r ent st at e i n Pr ef er ence obj ect
savePr ef er ences( ) ;
super.onPause();
}

protected void savePreferences(){
/ / cr eat e t he shar ed pr ef er ences obj ect
Shar edPr ef er ences myShar edPr ef er ences =
get Shar edPr ef er ences( MYPREFS, mode);

/ / obt ai n an edi t or t o add dat a t o ( my) Shar edPr ef er ences obj ect
Shar edPr ef er ences. Edi t or myEdi t or = myShar edPr ef er ences. edi t ( ) ;

/ / put some <key/ val ue> dat a i n t he pr ef er ences obj ect
myEdi t or . put St r i ng( " cust Name", "Mar i a Macar ena" ) ;
myEdi t or . put I nt ( " cust Age", 21) ;
myEdi t or . put Fl oat ( " cust Cr edi t " , 1500000. 00F) ;
myEdi t or . put Long( "cust Number ", 9876543210L) ;
myEdi t or . put St r i ng( " cust Dat eLast Cal l " , new Date().toLocaleString());
myEdi t or . commi t ( ) ;
}/ / savePr ef er ences
28
14. Android Preferences

Preferences

28


Example2: Saving/Retrieving a SharedPreference Object

public void showSavedPreferences() {
/ / r et r i eve t he Shar edPr ef er ences obj ect

Shar edPr ef er ences myShar edPr ef er ences =
get Shar edPr ef er ences( MYPREFS, mode);

/ / ext r act t he <key/ val ue> pai r s, use def aul t par amf or mi ssi ng dat a
cust Name = myShar edPr ef er ences. get St r i ng( " cust Name", " def NameVal ue" ) ;
cust Age = myShar edPr ef er ences. get I nt ( "cust Age" , 18) ;
cust Cr edi t = myShar edPr ef er ences. get Fl oat ( " cust Cr edi t " , 1000. 00F) ;
cust Number = myShar edPr ef er ences. get Long( " cust Number " , 1L) ;
cust Dat eLast Cal l = myShar edPr ef er ences. get St r i ng( " cust Dat eLast Cal l " ,
new Date().toLocaleString());
/ / show saved dat a on scr een
St r i ng msg = " name: " + cust Name + " \ nAge: " + cust Age +
" \ nCr edi t : " + cust Cr edi t +
" \ nLast Cal l : " + cust Dat eLast Cal l ;
t xt Pr ef . set Text ( msg) ;
}/ / l oadPr ef er ences

}/ / Pr ef er ences1

29 29
14. Android Preferences
Preferences
29
Questions ?

Das könnte Ihnen auch gefallen