Unit IV
Unit IV
Android
Persistency: Files
Victor Matos
Cleveland State University
Android Files
Android uses the same file constructions found
in a typical Java application.
2
15. Android – Files
Android Files
Your data storage options are the following:
3
15. Android – Files
Android Files
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);
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)
@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);
} // FilesDemo1
7
15. Android – Files
Android Files
Example2: (Internal Storage ) Read/Write an Internal File.
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;
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();
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
14
15. Android – Files
Android Files
Example 3: (External Storage)
Reading/Writing to the External Device’s SD card.
15
15. Android – Files
Android Files
WARNING: Writing to the Device’s SD card.
<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.
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.
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.*;
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
}// 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);
// 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
sdPath = Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ “/myFileName.txt” ;
28
10/11/2009
16
Android
External Resources
Victor Matos
Cleveland State University
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.
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
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.
Android Resources
Copy/Paste Resources
2
10/11/2009
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.
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
Android Resources
3
10/11/2009
Resources
Examples.
To see a number of samples you
should explore the folder:
c:\Android\platforms\android‐1.5\data\res\
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\
4
10/11/2009
Android Resources
Java Statements for Using Resources
Displaying a screen layout:
setContentView(R.layout.main);
setContentView(R.layout.screen2);
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
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:
11
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
Android Resources
Java Statements for Using Resources
Retrieving a drawable image from: res/drawable/…
/res/drawable/
imageView1.setImageResource(
R.drawable.android_green_3d);
13
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
Android Resources
Example1. Using Embedded Resources (drawable, string, array).
15
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;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//TRY: setContentView(R.layout.screen2);
16
8
10/11/2009
Android Resources
Example1. Using Embedded Resources (drawable, string, array).
EditText txtColorBox = (EditText)findViewById(R.id.txtColorBox);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
s2.setAdapter(adapter);
}
} 17
Android Resources
mmmm
18
9
10/11/2009
Android Resources
mmmm
19
Android Resources
mmmm
20
10
10/11/2009
21
Resources
Questions ?
22
11
10/11/2009
14
Android
Persistency: Preferences
Victor Matos
Cleveland State University
1. Preferences,
2. Files,
3. Databases, and
4. Network.
http://developer.android.com/guide/topics/data/data‐storage.html
2
1
10/11/2009
http://developer.android.com/guide/topics/data/data‐storage.html
3
2
10/11/2009
Preferences
Preferences is an Android lightweight mechanism to store
and retrieve key‐value pairs of primitive data types (also
called Maps, and Associative Arrays.
Preferences
Using Preferences API calls
You have three API choices to pick a Preference:
3
10/11/2009
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.
.getXXX(keyn)
Preference …
Container .getAll()
Keyy Value E
.putXXX(keyn, valuen)
D
I
T .remove(keyn)
O .clear()
R .commit()
7
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
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
Preferences
Example2: Saving/Retrieving a SharedPreference Object
5
10/11/2009
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
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;
6
10/11/2009
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
Preferences
Example2: Saving/Retrieving a SharedPreference Object
@Override
public void onClick(View v) {
// clear all previous selections
myEditor.clear();
14
7
10/11/2009
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
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
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
Preferences
Example: Saving/Retrieving a SharedPreference Object
Use DDMS to
see persistent
data set
18
9
10/11/2009
Preferences
Example: Saving/Retrieving a SharedPreference Object
19
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
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.*;
TextView captionBox;
EditText txtPref;
final int mode = Activity.MODE_PRIVATE;
21
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.");
11
10/11/2009
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();
}
Preferences
Example: Saving/Retrieving a SharedPreference 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
Preferences
Questions ?
25
13