Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
15 views52 pages

Unit IV

The document provides an overview of file persistency options in Android, including shared preferences, internal storage, external storage, and SQLite databases. It includes code examples for reading and writing files both in internal storage and on external SD cards, highlighting the need for permissions when accessing external storage. Additionally, it discusses the use of Java classes for file operations and offers practical examples for developers to implement in their applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views52 pages

Unit IV

The document provides an overview of file persistency options in Android, including shared preferences, internal storage, external storage, and SQLite databases. It includes code examples for reading and writing files both in internal storage and on external SD cards, highlighting the need for permissions when accessing external storage. Additionally, it discusses the use of Java classes for file operations and offers practical examples for developers to implement in their applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

15

Android
Persistency: Files

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
15. Android – Files

Android Files
Android uses the same file constructions found
in a typical Java application.

Files can be stored in the device’s (small) main


memory or in the much larger SD card. They can
also be obtained from the network (as we will see later).

Files stored in the device’s memory, stay together with other


application’s resources (such as icons, pictures, music, …).
We will call this type: Resource Files.

2
15. Android – Files

Android Files
Your data storage options are the following:

1. Shared Preferences Store private primitive data in key-value


pairs.
2. Internal Storage Store private data on the device memory.
3. External Storage Store public data on the shared external
storage.
4. SQLite Databases Store structured data in a private database.
5. Network Connection Store data on the web with your own
network server.

3
15. Android – Files

Android Files

Shared Preferences. Good for a few items saved as <Name, Value>


private void usingPreferences(){
// Save data in a SharedPreferences container
// We need an Editor object to make preference changes.

SharedPreferences settings = getSharedPreferences("my_preferred_Choices",


Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("favorite_color", "#ff0000ff");
editor.putInt("favorite_number", 101);
editor.commit();

// retrieving data from SharedPreferences container


String favColor = settings.getString("favorite_color", "default black");
int favNumber = settings.getInt("favorite_number", 0);

Toast.makeText(this, favColor + " " + favNumber, 1).show();

4
15. Android – Files

Android Files
Internal Storage. Using Android Resource Files
When an application’s .apk bytecode is deployed it may store in memory: code,
drawables, and other raw resources (such as files). Acquiring those resources
could be done using a statement such as:
InputStream is = this.getResources()
.openRawResource(R.drawable.my_base_data);

Use drag/drop to place file


my_base_data.txt in res folder.
It will be stored in the device’s
memory as part of the .apk

Spanish Pamgram
La cigüeña tocaba cada vez mejor el saxofón y el búho pedía kiwi y queso. 5
15. Android – Files

Android Files
Example 0: Reading a Resource File (see previous figure)

//reading an embedded RAW data file


package cis493.files;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import java.io.*;

public class FileDemo1Raw extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
PlayWithRawFiles();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Problems: " + e.getMessage(), 1).show();
}
}// onCreate 6
15. Android – Files

Android Files
Example 1: Reading a Resource File (see previous figure)
public void PlayWithRawFiles() throws IOException {
String str="";
StringBuffer buf = new StringBuffer();

InputStream is = this.getResources()
.openRawResource(R.drawable.my_base_data);

BufferedReader reader = new BufferedReader(


new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
Toast.makeText(getBaseContext(),
buf.toString(), Toast.LENGTH_LONG).show();
}// PlayWithRawFiles

} // FilesDemo1
7
15. Android – Files

Android Files
Example2: (Internal Storage ) Read/Write an Internal File.

In this example an application collects


data from the UI and saves it to a
persistent data file into the (limited) internal
Android System Space area.

Next time the application is executed the


Resource file is read and its data is shown
in the UI

8
15. Android – Files

Android Files
Example2: Grab from screen, save to file, retrieve from file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<Button android:id="@+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close" />

<EditText
android:id="@+id/editor"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:singleLine="false"
android:gravity="top"
/>

</LinearLayout>

9
15. Android – Files

Android Files
Example2: Grab from screen, save to file, retrieve from file.
package cis493.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Demo extends Activity {

private final static String NOTES="notes.txt";


private EditText editor;

10
15. Android – Files

Android Files
Example2: Grab from screen, save to file, retrieve from file.
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

setContentView(R.layout.main);
editor=(EditText)findViewById(R.id.editor);

Button btn=(Button)findViewById(R.id.close);

btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
finish();
}
});

}//onCreate

11
15. Android – Files

Android Files
Example2: Grab from screen, save to file, retrieve from file.
public void onResume() {
super.onResume();
try {
InputStream in=openFileInput(NOTES);
if (in!=null) {
InputStreamReader tmp=new InputStreamReader(in);
BufferedReader reader=new BufferedReader(tmp);
String str;
StringBuffer buf=new StringBuffer();

while ((str = reader.readLine()) != null) {


buf.append(str+"\n");
}
in.close();
editor.setText(buf.toString());
}//if
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast.makeText(this, "Exception: "+ t.toString(), 2000).show();
}
} 12
15. Android – Files

Android Files
Example2: Grab from screen, save to file, retrieve from file.
public void onPause() {
super.onPause();

try {
OutputStreamWriter out=
new OutputStreamWriter(openFileOutput(NOTES, 0));

out.write(editor.getText().toString());
out.close();
}
catch (Throwable t) {
Toast.makeText(this, "Exception: "+ t.toString(), 2000).show();
}
}

}//class

13
15. Android – Files

Android Files
File is stored in the phone’s memory under: /data/data/app/files

Image of the file


pulled from the
device

14
15. Android – Files

Android Files
Example 3: (External Storage)
Reading/Writing to the External Device’s SD card.

Storing data into the


SD card has the obvious
advantage of a larger
working space.

15
15. Android – Files

Android Files
WARNING: Writing to the Device’s SD card.

Since SDK1.6 it is necessary to request permission to write to the SD card.


Add the following clause to your AndroidManifest.xml

<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>

16
15. Android – Files

Android Files
Example 3: Reading/Writing to the Device’s SD card.

Assume the SD card in this example has been named sdcard. We will use the
Java.io.File class to designate the file’s path. The following fragment illustrates
the code strategy for output files.

File myFile = new File("/sdcard/mysdfile.txt");


myFile.createNewFile();

FileOutputStream fOut = new FileOutputStream(myFile);


OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();

17
15. Android – Files

Android Files
Example 3: Reading/Writing to the Device’s SD card.
<?xml version="1.0" encoding="utf-8"?> <Button
<LinearLayout android:id="@+id/btnClearScreen"
xmlns:android=http://schemas.android.com/apk android:layout_width="141px"
/res/android android:layout_height="42px"
android:id="@+id/widget28" android:text="2. Clear Screen" />
android:layout_width="fill_parent"
android:layout_height="fill_parent" <Button
android:background="#ff0000ff" android:id="@+id/btnReadSDFile"
android:orientation="vertical" android:layout_width="140px"
> android:layout_height="42px"
<EditText android:text="3. Read SD File" />
android:id="@+id/txtData"
android:layout_width="fill_parent" <Button
android:layout_height="180px" android:id="@+id/btnClose"
android:text="Enter some data here ..." android:layout_width="141px"
android:textSize="18sp" /> android:layout_height="43px"
android:text="4. Close" />
<Button
android:id="@+id/btnWriteSDFile" </LinearLayout>
android:layout_width="143px"
android:layout_height="44px"
android:text="1. Write SD File" />

18
15. Android – Files

Android Files
Example 3: Reading/Writing to the Device’s SD card.

19
15. Android – Files

Android Files
Example 3: Reading/Writing to the Device’s SD card.

Using DDMS File Explorer


panel to inspect the SD card.

20
15. Android – Files

Android Files
Example 3: Reading/Writing to the Device’s SD card.
package cis493.filedemo;
import java.io.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class FileDemo3SD extends Activity {


// GUI controls
EditText txtData;
Button btnWriteSDFile;
Button btnReadSDFile;
Button btnClearScreen;
Button btnClose;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here..."); 21
15. Android – Files

Android Files
Example 3: Reading/Writing to the Device’s SD card.
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// write on SD card file data from the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
} Toast.makeText(getBaseContext(),
e.getMessage(), Toast.LENGTH_SHORT).show();

}// onClick
}); // btnWriteSDFile 22
15. Android – Files

Android Files
Example 3: Reading/Writing to the Device’s SD card.
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// write on SD card file data from the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading SD 'mysdfile.txt'", 1).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), 1).show();
}
}// onClick
}); // btnReadSDFile
23
15. Android – Files

Android Files
Example 3: Reading/Writing to the Device’s SD card.
btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
btnClearScreen.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// clear text box
txtData.setText("");
}
}); // btnClearScreen

btnClose = (Button) findViewById(R.id.btnClose);


btnClose.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// clear text box
finish();
}
}); // btnClose

}// onCreate

}// class
24
15. Android – Files

Android Files
Example 3: Reading/Writing to the Device’s SD card. You may also use the
Scanner/PrintWriter classes, as suggested below:
private void testScannerFiles(){
// Add to manifest the following permission request
// <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
try {
String SDcardPath = Environment.getExternalStorageDirectory().getPath();
String mySDFileName = SDcardPath + "/" + "mysdfiletest.txt";
tvMessage.setText("Writing to: " + mySDFileName);
PrintWriter outfile= new PrintWriter( new FileWriter(mySDFileName) );
outfile.println("Hola Android");
outfile.println("Adios Android");
outfile.println(new Date().toString());
outfile.close();
// read SD-file,show records.
Scanner infile= new Scanner(new FileReader(mySDFileName));
String inString= "\n\nReading from: " + mySDFileName + "\n";
while(infile.hasNextLine()) {
inString += infile.nextLine() + "\n";
}
tvMessage.append(inString);
infile.close();
} catch (FileNotFoundException e) {
tvMessage.setText( "Error: " + e.getMessage());
} catch (IOException e) {
tvMessage.setText( "Error: " + e.getMessage());
}
} 25
15. Android – Files

Android Files
Example 4: Some more ideas on using the Scanner/PrintWriter classes.

// writing
FileOutputStream fos = openFileOutput("XYZ",
Context.MODE_PRIVATE);

PrintWriter outfile= new PrintWriter( fos );


outfile.println("Hola Android");
outfile.close();

// reading
InputStream is = openFileInput("XYZ");
Scanner infile= new Scanner(is);
String inString= "";
while(infile.hasNextLine()) {
inString = infile.nextLine();
}

26
15. Android – Files

Files
Questions ?

27
15. Android – Files

Files
Accessing the SD card

String spPath = “”;

sdPath = Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ “/myFileName.txt” ;

28
10/11/2009

16
Android
External Resources

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

16. Android – Resources

Android Resources
Resources and Internationalization

Resources are external files (that is, non‐code files) that are used by your code
and compiled into your application at build time.

Android supports a number of different kinds of resource files, including XML,


PNG, and JPEG files.

Resources are externalized from source code, and XML files are compiled into a
binary fast loading format for efficiency reasons
binary, reasons. Strings,
Strings likewise,
likewise are
compressed into a more efficient storage form.

http://developer.android.com/guide/topics/resources/resources‐i18n.html

1
10/11/2009

16. Android – Resources

Android Resources
Using Resources
The Android resource system
y keeps
p track of all non‐code assets associated with
an application.

You use the Resources class to access your application's resources; the
Resources instance associated with your application can generally be found
through Context.getResources().

To use a resource, you must install it correctly in the source tree and build your
application
application.

16. Android – Resources

Android Resources
Copy/Paste Resources

You will create and store your


y
resource files under the appropriate
subdirectory under the res/ directory
in your project.

Resources are compiled into the final


APK file.

Android creates a wrapper class,


class
called R, that you can use to refer to
these resources in your code. R
contains subclasses named according
to the path and file name of the
source file
4

2
10/11/2009

16. Android – Resources

Android Resources
Directory Resource Types

res/anim/ XML files that are compiled into frame by frame animation or tweened animation objects

res/drawable/ .png, .9.png, .jpg files. To get a resource of this type, use
mContext.getResources().getDrawable(R.drawable.imageId)

res/layout/ XML files that are compiled into screen layouts (or part of a screen).

res/values/ XML files that can be compiled into many kinds of resource.

arrays.xml to define arrays


colors.xml to define color drawables and color string values. Use Resources.getDrawable() and
Resources.getColor(), respectively, to get these resources.
dimens.xml to define dimension value. Use Resources.getDimension() to get these resources.
strings.xml
st gs to
o de
definee sstring
g values
a ues (use e
either
e Resources.getString
esou ces.getSt go
or p
preferably
e e ab y
Resources.getText() to get these resources. getText() will retain any rich text styling which is usually
desirable for UI strings.
styles.xml to define style objects.

res/xml/ Arbitrary XML files that are compiled and can be read at run time by calling Resources.getXML().

res/raw/ Arbitrary files to copy directly to the device. They are added uncompiled to the compressed file that your
application build produces. To use these resources in your application, call Resources.openRawResource()
with the resource ID, which is R.raw.somefilename

16. Android – Resources

Android Resources

A Typical Android Application consists of


Java code and additional resources merged
together into a deployable .apk file

3
10/11/2009

16. Android – Resources

Resources

Examples.
To see a number of samples you
should explore the folder:
c:\Android\platforms\android‐1.5\data\res\

16. Android – Resources

Resources

More Examples.
Try to install the ApiDemos
application. Explore its resource
folder. Find the source code in the
folder:
c:\Android\platforms\android‐1.6\samples\

How to install the App:


File ‐> New ‐> Project ‐> Android Project ‐> Next
Select "Create project form existing source"
Select the ApiDemos folder (all remaining fields will
be self adjusted)

4
10/11/2009

16. Android – Resources

Android Resources
Java Statements for Using Resources
Displaying a screen layout:

setContentView(R.layout.main);

setContentView(R.layout.screen2);

16. Android – Resources

Android Resources
Java Statements for Using Resources
Retrieving String Resources from: res/values/…

/res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hola Mundo!, ResourceDemo1!</string>
<string name="app_name">ResourceDemo1</string>
<string name="good_bye">Hasta luego</string>
<string name="color_caption">Color:</string>
<string name="color_prompt">Seleccione un Color</string>
<string name="planet_caption">
<b>Planeta </b>Planeta <i>Planeta </i><u>Planeta:
</u></string>
< t i
<string name="planet_prompt">Seleccione
" l t t">S l i un Planeta</string>
Pl t </ t i >
</resources>

String msg =
this.getString(R.string.color_prompt);

10

5
10/11/2009

16. Android – Resources

Android Resources
Java Statements for Using Resources
Enhancing externalized String resources from: res/values/…
//res/values/strings.xml
/ / g
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hola Mundo!, ResourceDemo1!</string>
<string name="app_name">ResourceDemo1</string>
<string name="good_bye">Hasta luego</string>
<string name="color_caption">Color:</string>
<string name="color_prompt">Seleccione un Color</string>
<string name="planet_caption">
<b>Planeta </b>Planeta <i>Planeta </i><u>Planeta: </u></string>
<string name="planet_prompt">Seleccione un Planeta</string>
</resources>

As in HTML a string using <b>, <i>, <u> modifiers will be rendered in: bold, italics,
and, underlined modes. In our example:

Planeta Planeta Planeta Planeta

11

16. Android – Resources

Android Resources
Java Statements for Using Resources
Retrieving Array Resources from: res/values/…

/res/values/arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<string-array name="planets">
<resources> <item>Mercury</item>
<item>Venus</item>
<string-array name="colors"> <item>Earth</item>
<item>red</item> <item>Mars</item>
<item>orange</item> <item>Jupiter</item>
<item>yellow</item> <item>Saturn</item>
<item>green</item> <item>Uranus</item>
<item>blue</item> <item>Neptune</item>
<item>violet</item> <item>Pluto</item>
</string-array> </string-array>

</resources>

String myColors[] =
this.getResources().getStringArray(R.array.colors);

12

6
10/11/2009

16. Android – Resources

Android Resources
Java Statements for Using Resources
Retrieving a drawable image from: res/drawable/…

/res/drawable/

//same as xml layout attribute


//android:src="@drawable/android_green_3d“

imageView1.setImageResource(
R.drawable.android_green_3d);

13

16. Android – Resources

Android Resources
Example1. Using Embedded Resources (drawable, string, array).
<?xml version
version="1.0"
1.0 encoding
encoding="utf-8"?>
utf 8 ?>
<LinearLayout <TextView
xmlns:android="http://schemas.android.com/apk/res/an android:layout_width="fill_parent"
droid" android:layout_height="wrap_content"
android:orientation="vertical" android:layout_marginTop="10dip"
android:padding="10dip" android:textSize="18px"
android:layout_width="fill_parent" android:text="@string/planet_caption"
android:layout_height="fill_parent" />
android:background="@color/solid_blue"
> <Spinner android:id="@+id/spinner2"
android:layout_width="fill_parent"
<ImageView android:layout_height="wrap_content"
android:id="@+id/ImageView01" android:drawSelectorOnTop="true"
android:layout_width="wrap_content" android:prompt="@string/planet_prompt"
android:layout_height="wrap_content" />
>
</ImageView> </LinearLayout>

<EditText
<?xml version="1.0" encoding="utf-8"?>
android:id="@+id/txtColorBox"
<resources>
android:layout_width="fill_parent"
<drawable name="red">#7f00</drawable>
android:layout_height="wrap_content"
<drawable name="blue">#770000ff</drawable>
/>
<drawable name="green">#7700ff00</drawable>
<color name="solid_red">#f00</color>
<color name="solid_blue">#0000ff</color>
<color name="solid_green">#f0f0</color>
/res/values/color.xml <color name="solid_yellow">#ffffff00</color>
</resources>
14

7
10/11/2009

16. Android – Resources

Android Resources
Example1. Using Embedded Resources (drawable, string, array).

15

16. Android – Resources

Android Resources
Example1. Using Embedded Resources (drawable, string, array).
// using Resources (adapted from Android - ApiDemos)
package cis493.resources;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

public class ResourceDemo1 extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//TRY: setContentView(R.layout.screen2);

ImageView imageView1 = (ImageView)findViewById(R.id.ImageView01);


//similar to xml layout android:src="@drawable/android_green_3d"
imageView1.setImageResource(R.drawable.android_green_3d);

16

8
10/11/2009

16. Android – Resources

Android Resources
Example1. Using Embedded Resources (drawable, string, array).
EditText txtColorBox = (EditText)findViewById(R.id.txtColorBox);

String msg = this.getString(R.string.color_caption);


this.getString(R.string.color caption);

String myColors[] = this.getResources().getStringArray(R.array.colors);

for ( int i=0; i<myColors.length; i++){


msg += "\n\t" + myColors[i];
}
txtColorBox.setText(msg);

Spinner s2 = (Spinner) findViewById(R.id.spinner2);


A
ArrayAdapter<CharSequence>
Ad t <Ch S > adapter
d t = ArrayAdapter.createFromResource(
A Ad t t F R (
this,
R.array.planets,
android.R.layout.simple_spinner_item);

adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
s2.setAdapter(adapter);
}
} 17

16. Android – Resources

Android Resources
mmmm

18

9
10/11/2009

16. Android – Resources

Android Resources
mmmm

19

16. Android – Resources

Android Resources
mmmm

20

10
10/11/2009

21

16. Android – Resources

Resources
Questions ?

22

11
10/11/2009

14
Android
Persistency: Preferences

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

14. Android – Preferences

Android Data Storage

Android provides the following four mechanisms for


storing and retrieving data:

1. Preferences,
2. Files,
3. Databases, and
4. Network.

http://developer.android.com/guide/topics/data/data‐storage.html
2

1
10/11/2009

14. Android – Preferences

Android Data Storage

A typical desktop operating system provides a common


file system that any application can use to store files that
can be read by other applications (perhaps with some
access control settings).

Android uses a different system:


On Android,, all application
pp data ((including
g ffiles)) are
private to that application.

http://developer.android.com/guide/topics/data/data‐storage.html
3

14. Android – Preferences

Android Data Storage


Android also provides a standard way for an application
to expose
p its p
private data to other applications
pp — through
g
content providers.

Android supplies a number of content providers for


standard data types, such as
image,
audio,
d
video files and
personal contact information.

2
10/11/2009

14. Android – Preferences

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

Typically used to keep state information and shared data


among several activities of an application.

On each entry <key‐value>


<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. 5

14. Android – Preferences

Preferences
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

3
10/11/2009

14. Android – Preferences

Preferences
Using Preferences API calls
All of the get… 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
container.

XXX = { Long, Int, Double, Boolean, String }

.getXXX(keyn)
Preference …
Container .getAll()
Keyy Value E
.putXXX(keyn, valuen)
D
I
T .remove(keyn)
O .clear()
R .commit()
7

14. Android – Preferences

Preferences
Example
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 application’s name‐space.
8

4
10/11/2009

14. Android – Preferences

Preferences
Example2: Saving/Retrieving a SharedPreference Object holding UI user choices.

Initial UI with no choices Images of the choices made by the user regarding the
Made/save yet. 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. 9

14. Android – Preferences

Preferences
Example2: Saving/Retrieving a SharedPreference Object

Image of the preference file


(obtained by pulling a copy of
the file out of the device).
Using DDMS to explore the Device’s memory map.
Observe the choices made by the user are saved in
the data/data/Shared_prefs/ folder as an XML file.
10

5
10/11/2009

14. Android – Preferences

Preferences
Example2: Saving/Retrieving a SharedPreference Object
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/linLayout1Vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" >

<LinearLayout
android:id="@+id/linLayout2Horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content“ >
<Button
android:id="@+id/btnPrefSimple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pref Simple UI“ />
<Button
android:id="@+id/btnPrefFancy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pref Fancy UI“ />
</LinearLayout>

<TextView
android:id="@+id/txtCaption1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff006666"
android:text="This is some sample text “ />

</LinearLayout>
11

14. Android – Preferences

Preferences
Example2: Saving/Retrieving a SharedPreference Object
package cis493.preferences;
import java.util.Date;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class PreferenceDemo0 extends Activity implements OnClickListener {


Button btnSimplePref;
Button btnFancyPref;
TextView txtCaption1;
Boolean fancyPrefChosen = false;
View myLayout1Vertical;
final int mode = Activity.MODE_PRIVATE;
final String MYPREFS = "MyPreferences_001";
// create a reference to the shared preferences object
SharedPreferences mySharedPreferences;
// obtain an editor to add data to my SharedPreferences object
SharedPreferences.Editor myEditor;
12

6
10/11/2009

14. Android – Preferences

Preferences
Example2: Saving/Retrieving a SharedPreference Object
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myLayout1Vertical = (View)findViewById(R.id.linLayout1Vertical);
txtCaption1 = (TextView) findViewById(R.id.txtCaption1);
txtCaption1.setText("This is a sample line \n“
+ "suggesting the way the UI looks \n"
+ "after you choose your preference");
// create a reference & editor for the shared preferences object
mySharedPreferences = getSharedPreferences(MYPREFS, 0);
myEditor = mySharedPreferences.edit();
// has a Preferences file been already created?
if (mySharedPreferences != null
&& mySharedPreferences.contains("backColor")) {
// object and key found
found, show all saved values
applySavedPreferences();
} else {
Toast.makeText(getApplicationContext(),
"No Preferences found", 1).show();
}
btnSimplePref = (Button) findViewById(R.id.btnPrefSimple);
btnSimplePref.setOnClickListener(this);
btnFancyPref = (Button) findViewById(R.id.btnPrefFancy);
btnFancyPref.setOnClickListener(this);
}// onCreate 13

14. Android – Preferences

Preferences
Example2: Saving/Retrieving a SharedPreference Object
@Override
public void onClick(View v) {
// clear all previous selections
myEditor.clear();

// what button has been clicked?


if (v.getId() == btnSimplePref.getId()) {
myEditor.putInt("backColor", Color.BLACK);// black background
myEditor.putInt("textSize", 12); // humble small font
} else { // case btnFancyPref
myEditor.putInt("backColor", Color.BLUE); // fancy blue
myEditor.putInt("textSize", 20); // fancy big
myEditor.putString("textStyle", "bold"); // fancy bold
myEditor.putInt("layoutColor", Color.GREEN);//fancy green
}
myEditor.commit();
applySavedPreferences();
}

14

7
10/11/2009

14. Android – Preferences

Preferences
Example2: Saving/Retrieving a SharedPreference Object
@Override
protected void onPause() {
// warning: activity is on its last state of visibility!.
// It's
It s on the edge of been killed! Better save all current
// state data into Preference object (be quick!)
myEditor.putString("DateLastExecution", new Date().toLocaleString());
myEditor.commit();
super.onPause();
}

15

14. Android – Preferences

Preferences
Example2: Saving/Retrieving a SharedPreference Object
public void applySavedPreferences() {
// extract the <key/value> pairs, use default param for missing data
int backColor = mySharedPreferences.getInt("backColor",Color.BLACK);
int textSize = mySharedPreferences.getInt(
mySharedPreferences.getInt("textSize",
textSize , 12);
String textStyle = mySharedPreferences.getString("textStyle", "normal");
int layoutColor = mySharedPreferences.getInt("layoutColor",
Color.DKGRAY);
String msg = "color " + backColor + "\n"
+ "size " + textSize + "\n"
+ "style " + textStyle;
Toast.makeText(getApplicationContext(), msg, 1).show();

txtCaption1.setBackgroundColor(backColor);
txtCaption1.setTextSize(textSize);
if (textStyle.compareTo("normal")==0){
(textStyle compareTo("normal")==0){
txtCaption1.setTypeface(Typeface.SERIF,Typeface.NORMAL);
}
else {
txtCaption1.setTypeface(Typeface.SERIF,Typeface.BOLD);
}
myLayout1Vertical.setBackgroundColor(layoutColor);
}// applySavedPreferences

}//class 16

8
10/11/2009

14. Android – Preferences

Preferences
Example3: Saving/Retrieving a SharedPreference Object containing ‘business’ data.

Image of the data held in the Image of the saved Preference data
SharedPreferences object displayed the second time the
displayed the first time the Activity Activity Preferences1 is executed.
Preferences1 is executed. 17

14. Android – Preferences

Preferences
Example: Saving/Retrieving a SharedPreference Object

Use DDMS to
see persistent
data set

18

9
10/11/2009

14. Android – Preferences

Preferences
Example: Saving/Retrieving a SharedPreference Object

Persistent data is saved in


the phone’s memory as an
XML file. This image was
pulled from the device
using DDMS.

19

14. Android – Preferences

Preferences
Example: Saving/Retrieving a SharedPreference Object
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/linLayou1"
android:layout width="fill
android:layout_width fill_parent
parent"
android:layout_height="fill_parent"
android:background="#ff0000ff"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/captionBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SharedPreferences Container: Customer Data"
android:layout margin="5px" android:textStyle="bold">
android:layout_margin="5px"
</TextView>
<EditText
android:id="@+id/txtPref"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10px"
>
</EditText>
</LinearLayout> 20

10
10/11/2009

14. Android – Preferences

Preferences
Example: 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";
//this data values describe a typical customer record
String custName = "n.a.";
int custAge = 0;
float custCredit = 0;
long custNumber = 0;
String custDateLastCall;

TextView captionBox;
EditText txtPref;
final int mode = Activity.MODE_PRIVATE;

21

14. Android – Preferences

Preferences
Example: Saving/Retrieving a SharedPreference Object

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
i ( l i )
txtPref = (EditText)findViewById(R.id.txtPref);
captionBox = (TextView) findViewById(R.id.captionBox);
captionBox.setText("SharedPreference Container: \n\n"+
"we are working on customer Macarena \n" +
"fake an interruption, press 'Back Button' \n" +
"re-execute the application.");

//create a reference to the shared preferences object


int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS, mode);
//is there an existing
// g Preferences from p
previous executions of this app?
pp
if (mySharedPreferences != null &&
mySharedPreferences.contains("custName")) {
//object and key found, show all saved values
showSavedPreferences();
}
else
{
txtPref.setText("nada");
}
}//onCreate 22

11
10/11/2009

14. Android – Preferences

Preferences
Example: Saving/Retrieving a SharedPreference Object
@Override
protected void onPause() {
//warning: activity is on last state of visibility! We are on the
//edge of been killed! Better save current state in Preference object
savePreferences();
super.onPause();
}

protected void savePreferences(){


//create the shared preferences object
SharedPreferences mySharedPreferences =
getSharedPreferences(MYPREFS, mode);

//obtain an editor to add data to (my)SharedPreferences object


SharedPreferences.Editor
SharedPreferences Editor myEditor = mySharedPreferences.edit();
mySharedPreferences edit();

//put some <key/value> data in the preferences object


myEditor.putString("custName", "Maria Macarena");
myEditor.putInt("custAge", 21);
myEditor.putFloat("custCredit", 1500000.00F);
myEditor.putLong("custNumber", 9876543210L);
myEditor.putString("custDateLastCall", new Date().toLocaleString());
myEditor.commit();
}//savePreferences 23

14. Android – Preferences

Preferences
Example: Saving/Retrieving a SharedPreference Object

public void showSavedPreferences() {


//retrieve the SharedPreferences object

SharedPreferences mySharedPreferences =
getSharedPreferences(MYPREFS, mode);

//extract the <key/value> pairs, use default param for missing data
custName = mySharedPreferences.getString("custName", "defNameValue");
custAge = mySharedPreferences.getInt("custAge", 18);
custCredit = mySharedPreferences.getFloat("custCredit", 1000.00F);
custNumber = mySharedPreferences.getLong("custNumber", 1L);
custDateLastCall = mySharedPreferences.getString("custDateLastCall",
new Date().toLocaleString());
//show saved data on screen
String msg = "name: " + custName + "\nAge: " + custAge +
"\nCredit: " + custCredit +
"\nLastCall: " + custDateLastCall;
txtPref.setText(msg);
}//loadPreferences

}//Preferences1
24

12
10/11/2009

14. Android – Preferences

Preferences
Questions ?

25

13

You might also like