Android 4
Android 4
References
Google Android Documentation, http://code.google.com/android/documentation.html
PersonEditor
Displays/Edits age
Go button
Calls PersonEditor
Passes data
Name
Age
Done button
Returns edited data back
Age = 0 cancels edit
IntentExample.java
public class IntentExample extends Activity implements View.OnClickListener {
private EditText numberText;
private static final int INTENT_EXAMPLE_REQUEST = 123;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intent);
Button ok = (Button) findViewById(R.id.go);
ok.setOnClickListener(this);
numberText = (EditText) this.findViewById(R.id.number);
numberText.setText("21");
}
When we want a reply back from an Intent request we supply a request number. The request number is return with the answer.
That way it is possible to know where the request originated from.
IntentExample.Java continued
Sending the data to PersonEditor
The name was sent just to show we can send multiple items. They can be of any base type or serializable. See the putExtra
methods in the Intent class.
IntentExample.Java continued
Getting the Results back
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != INTENT_EXAMPLE_REQUEST) {
numberText.setText("Not from me");
return;
}
switch (resultCode) {
case RESULT_OK:
String editedAge = data.getStringExtra("age");
numberText.setText(editedAge);
break;
case RESULT_CANCELED:
numberText.setText("Cancelled");
break;
}
}
}
6
When an activity is started after a return from a startActivityForResult request, the method onActivityResult is called. The
requestCode is the request code sent in the startActivityForResult method. The result code is the set by the called activity and is
RESULT_OK or RESULT_CANCELED by convention. The intent is used to send data back to this activity. RESULT_OK and
RESULT_CANCELED are constants defined in the Activity class.
PersonEditor.java
public class PersonEditor extends Activity implements View.OnClickListener {
private EditText ageText;
private EditText nameText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.person_editor);
Button done = (Button) findViewById(R.id.edit_done);
done.setOnClickListener(this);
ageText = (EditText) this.findViewById(R.id.edit_age);
nameText = (EditText) this.findViewById(R.id.edit_name);
Bundle personData = getIntent().getExtras();
String age = personData.getString("age");
String name = personData.getString("name");
if ((age != null) && (name != null)) {
ageText.setText(age);
nameText.setText(name);
}
}
7
Showing how to access the intent that started the activity and extracting the extras from the intent. If the key-value pair was
not set in the intent the value will be returned as null.
PersonEditor.java
Returning the data
setResult(int, Intent) returns information to the calling activity. The first parameter is the result code passed back in
onActivityResult. The intent is the intent passed back in onActivityResult.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.sdsu.cs683.example" android:versionCode="1"
android:versionName="1.0.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".IntentExample" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The intent filter for the activity must contain all the categories used by the intent to select the activity. It can contain more
categories. The example does not work without the default category.
Data Storage
10
Data Topics
Preferences
Files
SQLite database
Content Providers
Network
11
Preferences
Key value pairs for program
Key - string
Value
boolean
float
int
long
string
getPreferences(int mode)
For access in activity only
getSharedPreferences(String name,int mode)
To share preferences with other activities
mode
0 = MODE_PRIVATE
MODE_WORLD_READABLE
MODE_WORLD_WRITEABLE
12
Example
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
protected void onCreate(Bundle state){
super.onCreate(state);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
protected void onStop(){
super.onStop();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
editor.commit();
}
}
13
Files
Application can write/read files on phone
Cannot directly read files written by other application
Write a file
FileOutputStream openFileOutput(String name, int mode)
Creates file if it does not exist
mode
0 = MODE_PRIVATE
MODE_APPEND
MODE_WORLD_READABLE
MODE_WORLD_WRITEABLE
FileInputStream openFileInput(String name)
name can not contain path seperators
14
Static files
You can package static files with your application
Place file in res/raw/<mydatafile>
Generates resource id in R
Read file using
Resources.openRawResource (R.raw.mydatafile)
15
File Example
16
FileExample Structure
public class FileExamples extends Activity implements View.OnClickListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button update = (Button) findViewById(R.id.update);
update.setOnClickListener(this);
restoreData();
}
public void onClick(View v) {
saveData();
}
17
18
Read file
private String readFile() {
String fileContents;
try {
InputStream file = new BufferedInputStream(
openFileInput("dataFile"));
byte[] data = new byte[file.available()];
file.read(data, 0, file.available());
fileContents = new String(data);
file.close();
} catch (Exception noFile) {
fileContents = "empty";
}
return fileContents;
}
19
20
Writing a File
21
Database
22
Database
SQLite
Embedded SQL database engine
Free
Source is in public domain
Transactions
File format is cross-platform
http://www.sqlite.org/index.html
23
24
SQLiteOpenHelper
synchronized void close()
Close any open database object.
synchronized SQLiteDatabase getReadableDatabase()
Create and/or open a database.
synchronized SQLiteDatabase getWritableDatabase()
Create and/or open a database that will be used for reading and writing.
abstract void onCreate(SQLiteDatabase db)
Called when the database is created for the first time.
void onOpen(SQLiteDatabase db)
Called when the database has been opened.
abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
Called when the database needs to be upgraded.
25
Android Databases
Accessable to all classes in an application
Can't access directly databases from other applications
Database errors are logged
Can connect to database on phone from shell
http://code.google.com/android/reference/adb.html#sqlite
26
Example
Show
Creating database
Inserts
Update
Delete
Query
27
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "name.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase nameDb) {
nameDb.execSQL("CREATE TABLE " + "NAMES" + " ("
+ "_ID" + " INTEGER PRIMARY KEY,"
+ "NAME" + " TEXT"
+ ");");
nameDb.execSQL("INSERT INTO NAMES ( name) VALUES ('Roger' );");
}
public void onUpgrade(SQLiteDatabase arg0, int oldVersion, int newVersion) {
}
}
28
DatabaseExample.java
private void displayDatabaseRecord(int id) {
displayDatabaseRecord(String.valueOf(id));
}
private void displayDatabaseRecord(String id) {
SQLiteDatabase nameDb = namesHelper.getWritableDatabase();
Cursor result = nameDb.rawQuery("select * from NAMES where _ID = ?",
new String[] { id });
int rowCount = result.getCount();
if (rowCount > 0) {
result.moveToFirst();
databaseIdText.setText(String.valueOf(result.getInt(0)));
nameText.setText(result.getString(1));
}
}
30
DatabaseExample.java
31
DatabaseExample.java
public void onClick(View clicked) {
SQLiteDatabase db = namesHelper.getWritableDatabase();
switch (clicked.getId()) {
case R.id.read:
displayDatabaseRecord(getId());
break;
case R.id.delete:
db.delete("NAMES", "_ID = ?", new String[] { getId() });
break;
32
onClick
case R.id.insert:
ContentValues newName = new ContentValues(1);
newName.put("NAME", getName());
db.insert("NAMES", null, newName);
break;
case R.id.update:
ContentValues updateName = new ContentValues(1);
updateName.put("NAME", getName());
db.update("NAMES", updateName, "_ID = ?", new String[] { getId() });
break;
}
}
}
33