Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept....

58
App Development for Smart Devices CS 495/595 - Fall 2013 Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider

Transcript of Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept....

Page 1: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

App Development for Smart Devices � �

CS 495/595 - Fall 2013 �

Tamer Nadeem �Dept. of Computer Science�

Lec #3: Files, Preferences, and Content Provider �

Page 2: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 2 Fall 2013 CS 495/595 - App Development for Smart Devices

• Data Storage • Shared Preferences � Data Files

• SQLite � Content Provider

• Discussion on Project Ideas

Objective

Page 3: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 3 Fall 2013 CS 495/595 - App Development for Smart Devices

• Your options (most complex apps use all) – Shared Preferences

– Bundles

– Local files

– Local database (SQLite)

– Remote database

• Saving data obviously essential

Saving data

Page 4: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 4 Fall 2013 CS 495/595 - App Development for Smart Devices

• Activity should save its user interface state each time it moves to the background

– Required due to OS killing processes

– Even if you think your app will be in the foreground all the time, you need to do this, because of....

•  Phone calls

•  Other apps

•  The nature of mobile use

Saving UI state

Page 5: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 5 CS 495/595 - App Development for Smart Devices Fall 2013

Shared Preferences

Page 6: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 6 Fall 2013 CS 495/595 - App Development for Smart Devices

• Simple, lightweight key/value pair (or name/value pair NVP) mechanism

• Support primitive types: Boolean, string, float, long and integer • Stored as XML in the protected application directory on main

memory (/data/data/<package name>/shared_prefs/<YOUR_PREFS_NAME>.xml)

• Shared among application components running in the same application context

Shared Preferences

//Getting Context example public class MyActivity extends Activity { public void method() { Context actContext = this; // since Activity extends Context Context appContext = getApplicationContext();

Context vwContext = ((Button)findViewById(R.id.btn_id)).getContext(); } }

Page 7: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 7 Fall 2013 CS 495/595 - App Development for Smart Devices

DDMS-File Explorer (Window > Open Perspective > Other... > DDMS)

http://developer.android.com/guide/developing/debugging/ddms.html

Page 8: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 8 Fall 2013 CS 495/595 - App Development for Smart Devices

Creating and Sharing Prefs public static String MY_PREFS = ”YOUR_PREFS_NAME";

int mode = Activity.MODE_PRIVATE; SharedPreferences mySharedPreferences =

getSharedPreferences(MY_PREFS, mode);

SharedPreferences.Editor editor = mySharedPreferences.edit();

// Store new primitive types in the shared preferences object. editor.putBoolean("isTrue", true); editor.putFloat("lastFloat", 1f); editor.putInt("wholeNumber", 2); editor.putLong("aNumber", 3l); editor.putString("textEntryValue", "Not Empty");

// Commit the changes. editor.commit();

Page 9: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 9 Fall 2013 CS 495/595 - App Development for Smart Devices

Retrieving Prefs public static String MY_PREFS = "YOUR_PREFS_NAME"; public void loadPreferences() {

// Get the stored preferences int mode = Activity.MODE_PRIVATE; SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS, mode);

// Retrieve the saved values. boolean isTrue = mySharedPreferences.getBoolean("isTrue", false); float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f); int wholeNumber = mySharedPreferences.getInt("wholeNumber", 1); long aNumber = mySharedPreferences.getLong("aNumber", 0); String stringPreference = mySharedPreferences.getString("textEntryValue", ""); }

Page 10: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 10 Fall 2013 CS 495/595 - App Development for Smart Devices

• System-style preference screens

– Familiar

– Can merge settings from other apps (e.g., system settings such as location)

• 3 parts

– Preference Screen Layout (XML)

– Extension of PreferenceActivity

– onSharedPreferenceChangeListener

PreferenceActivity

Page 11: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 11 Fall 2013 CS 495/595 - App Development for Smart Devices

PreferenceActivity

<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen

xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="My Preference Category"/> <CheckBoxPreference android:key="PREF_CHECK_BOX" android:title="Check Box Preference" android:summary="Check Box Preference Description" android:defaultValue="true" /> </PreferenceCategory>

</PreferenceScreen>

• XML (e.g., stored as R/xml/preferences.xml)

Page 12: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 12 Fall 2013 CS 495/595 - App Development for Smart Devices

• Options

– CheckBoxPreference

– EditTextPreference

– ListPreference

– RingtonePreference

PreferenceActivity

Page 13: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 13 Fall 2013 CS 495/595 - App Development for Smart Devices

PreferenceActivity

Public class MyPreferenceActivity extends PreferenceActivity {

@Override Public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); }

}

In manifest... <activity android:name=“.MyPreferenceActivity”

android:label=“My Preferences”>

To start... Intent I = new Intent(this, MyPreferenceActivity.class); startActivityForResult(i, SHOW_PREFERENCES);

Page 14: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 14 Fall 2013 CS 495/595 - App Development for Smart Devices

Default Prefs

Context context = getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // then Retrieve values using get<type> method

• Default shared prefs are stored in Application Context. Therefore, available to any component:

– Activities – Services – BroadcastReceiver

(/data/data/<package name>/shared_prefs/<package name>_preferences.xml)

• Default shared prefs location:

Page 15: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 15 Fall 2013 CS 495/595 - App Development for Smart Devices

• Run some code whenever a Shared Preference value is added, removed, modified • Useful for Activities or Services that use SP framework to set application preferences

Prefs change listeners

Page 16: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 16 Fall 2013 CS 495/595 - App Development for Smart Devices

SP change listeners

public class MyActivity extends Activity implements OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle SavedInstanceState) { // Register this OnSharedPreferenceChangeListener Context context = getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.registerOnSharedPreferenceChangeListener(this); }

public void onSharedPreferenceChanged(SharedPreferences prefs,

String key) { // TODO Check the shared preference and key parameters // and change UI or behavior as appropriate.

} }

Page 17: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 17 CS 495/595 - App Development for Smart Devices Fall 2013

Bundles

Page 18: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 18 Fall 2013 CS 495/595 - App Development for Smart Devices

• Activities offer onSaveInstanceState handler – Works like SharedPreferences – Bundle parameter represents key/value map of primitive types that can be used save the Activity’s instance values – Bundle made available as a parameter passed in to the onCreate and onRestoreInstance method handlers – Bundle stores info needed to recreate UI state

Bundles

Page 19: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 19 Fall 2013 CS 495/595 - App Development for Smart Devices

Saving Bundle @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted. savedInstanceState.putBoolean("MyBoolean", true); savedInstanceState.putDouble("myDouble", 1.9); savedInstanceState.putInt("MyInt", 1); savedInstanceState.putString("MyString", "Welcome back to Android"); // etc.

super.onSaveInstanceState(savedInstanceState); }

Page 20: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 20 Fall 2013 CS 495/595 - App Development for Smart Devices

Restoring Bundle @Override public void onRestoreInstanceState(Bundle savedInstanceState) {

super.onRestoreInstanceState(savedInstanceState);

// Restore UI state from the savedInstanceState. // This bundle has also been passed to onCreate. boolean myBoolean = savedInstanceState.getBoolean("MyBoolean"); double myDouble = savedInstanceState.getDouble("myDouble"); int myInt = savedInstanceState.getInt("MyInt"); String myString = savedInstanceState.getString("MyString");

}

Page 21: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 21 CS 495/595 - App Development for Smart Devices Fall 2013

Data Files

Page 22: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 22 Fall 2013 CS 495/595 - App Development for Smart Devices

Saving/loading files

String FILE_NAME = "tempfile.tmp"; // Create a new output file stream that’s private to this application. FileOutputStream fos = openFileOutput(FILE_NAME,

Context.MODE_PRIVATE); // Open input file stream. FileInputStream fis = openFileInput(FILE_NAME);

• Biggest decision: location

– Local vs Remote

– Internal vs External

• Code is standard Java

Page 23: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 23 Fall 2013 CS 495/595 - App Development for Smart Devices

• Can only write in current application folder (/data/data/<package_name>/files/<filename>) or external storage (e.g., /mnt/sdcard/<filename>)

– Exception thrown otherwise

• For external, must be careful about availability of storage card

– Behavior when docked – Cards get wiped

Saving/loading files

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

</uses-permission>

• SD Card Writing Permission (AndroidManifest.xml)

Page 24: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 24 Fall 2013 CS 495/595 - App Development for Smart Devices

Check SD card! private static final String ERR_SD_MISSING_MSG = “ERRSD cannot see your SD card.

Please reinstall it and do not remove it."; private static final String ERR_SD_UNREADABLE_MSG = "CITY cannot read your SD

(memory) card. This is probably because your phone is plugged into your computer. Please unplug it and try again.";

public static String getSDCard() throws ERRSDException { if (Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)) throw new ERRSDException(ERR_SD_MISSING_MSG); else if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) throw new ERRSDException(ERR_SD_UNREADABLE_MSG);

File sdCard = Environment.getExternalStorageDirectory(); // “/mnt/sdcard” if (!sdCard.exists()) throw new ERRSDException(ERR_SD_MISSING_MSG); if (!sdCard.canRead()) //for writing à sdCard.canWrite() throw new ERRSDException(ERR_SD_UNREADABLE_MSG);

return sdCard.toString(); }

Page 25: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 25 CS 495/595 - App Development for Smart Devices Fall 2013

SQLite

Page 26: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 26 Fall 2013 CS 495/595 - App Development for Smart Devices

• Embedded database for Android

• Supports 3 main data types – TEXT (like Java String) – INTEGER (like Java long) – REAL (like Java double)

• No type checking inherent in SQLite

• Each DB is private to App that created it

• Data Stored at: •  /data/data/<package name>/databases/<db name>

SQLite

Documentation on SQLITE available at: http://www.sqlite.org/sqlite.html Good GUI tool for SQLITE available at: http://sqliteadmin.orbmu2k.de/ SQL and SQLite Language Syntax at: http://www.sqlite.org/lang.html

Page 27: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 27 Fall 2013 CS 495/595 - App Development for Smart Devices

• Create a subclass of SQLiteOpenHelper – Override at least onCreate() - where you can create tables

– Can also override onUpgrade() - make a modification to the tables structures

• Call getWritableDatabase() to get read/write instance of SQLiteDatabase

– Can then call insert(), delete(), update()

Using SQLite

Page 28: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 28 Fall 2013 CS 495/595 - App Development for Smart Devices

Subclass SQLiteOpenHelper public class DatabaseHelper extends SQLiteOpenHelper { static final String dbName="demoDB"; static final int dbVersion=1; static final String employeeTable="Employees"; static final String colID="EmployeeID"; static final String colName="EmployeeName"; static final String colAge="Age"; static final String colDept="Dept";

static final String deptTable="Dept"; static final String colDeptID="DeptID"; static final String colDeptName="DeptName";

public DatabaseHelper(Context context) { super(context, dbName, null, dbVersion); } … }

Page 29: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 29 Fall 2013 CS 495/595 - App Development for Smart Devices

onCreate(SQLiteDatabase db)

public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE “ + deptTable + " (“ +

colDeptID + “ INTEGER, “ + colDeptName + " TEXT);"); db.execSQL("CREATE TABLE "+ employeeTable + " (“ +

colID + “ INTEGER, “ + colName + “ TEXT, “ + colAge + " INTEGER, “ + colDept + " INTEGER);");

}

Page 30: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 30 Fall 2013 CS 495/595 - App Development for Smart Devices

Handling Records SQLiteDatabase db=this.getWritableDatabase();

//Inserting Records ContentValues cv=new ContentValues(); cv.put(colDeptID, 1); cv.put(colDeptName, "Sales"); db.insert(deptTable, colDeptID, cv);

db.execSQL( “INSERT INTO “ + deptTable + “(“ + colDeptID + “,” + colDeptName + “) values (‘2', ‘Services' );" );

//Deleting Record db.delete(deptTable, colDeptID + "=" + dept_1, null); //dept_1=“1”

//Updating Record cv.put(colDeptName, “newIT”); db.update(deptTable, cv, colDeptID + "=?", dept_2); //dept_2=“2”

db.close();

http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

Page 31: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 31 Fall 2013 CS 495/595 - App Development for Smart Devices

SQL Select Syntax (see http://www.sqlite.org/lang.html) SQL-select statements are based on the following components

Querying SQL

The first two lines are mandatory, the rest is optional.

Page 32: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 32 Fall 2013 CS 495/595 - App Development for Smart Devices

• SQLiteDatabase.query() returns a Cursor object that points to results

– Cursor is a iterator. Call moveToNext() to get to next element.

– Cursor can be examined at runtime

•  getCount(), getColumnCount()

•  getColumnIndex(String name)

•  getColumnName(int index)

•  getInt(int index), getLong(int index), getString(int index), etc.

Querying SQLite

Page 33: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 33 Fall 2013 CS 495/595 - App Development for Smart Devices

Android Simple Queries The signature of the Android’s simple query method is:

Querying SQLite – query()

http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

Page 34: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 34 Fall 2013 CS 495/595 - App Development for Smart Devices

Android Simple Queries Example Query the EmployeeTable, find the average salary of female employees supervised by 123456789. Report results by Dno. List first the highest average, and so on, do not include depts. having less than two employees.

Querying SQLite - Example

Page 35: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 35 Fall 2013 CS 495/595 - App Development for Smart Devices

Cursor - Example

Page 36: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 36 CS 495/595 - App Development for Smart Devices Fall 2013

Content Provider

Page 37: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 37 Fall 2013 CS 495/595 - App Development for Smart Devices

• A content provider makes a specific set of the application's data available to other applications

=> Share data to other apps

• Any app with appropriate permission, can read and write the data.

• Many native databases are available via the content providers, for example Contact Manager

• Common interface for querying the data

Content Provider

Page 38: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 38 Fall 2013 CS 495/595 - App Development for Smart Devices

• Content providers expose their data as a simple table on a database model

• Every record includes a numeric _ID field that uniquely identifies the record within the table.

About Content Provider

Page 39: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 39 Fall 2013 CS 495/595 - App Development for Smart Devices

• Content provider exposes a public URI that uniquely identifies its data set:

content://<Authority>/[data_path]/[instance identifier] •  the URI starts with content:// scheme.

•  Authority is a unique identifier for the content provider. Example “contacts”.

•  data_path specifies the kind of data requested. For example, “people” is used to refer to all the contacts within “contacts”.

•  there can be an instance identifier that refers to a specific data instance.

•  content://media/internal/images - return the list of all internal images on the device.

•  content://media/external/images - return the list of all the images on external storage (e.g., SD card) on the device.

•  content://call_log/calls - return a list of all the calls registered in the call log.

•  content://browser/bookmarks - return a list of bookmarks stored in the browser.

•  content://contacts/people/45 - return the single result row, the contact with ID=45.

About Content Provider

Page 40: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 40 Fall 2013 CS 495/595 - App Development for Smart Devices

•  Browser—Read or modify bookmarks, browser history, or web searches.

•  CallLog—View or update the call history.

•  Contacts—Retrieve, modify, or store the personal contacts. Three-tier data model of tables under a ContactsContract object:

•  ContactsContract.Data—Contains all kinds of personal data. •  ContactsContract.RawContacts—Contains a set of Data objects associated

with a single account or person. •  ContactsContract.Contacts—Contains an aggregate of one or more

RawContacts, presumably describing the same person.

•  MediaStore—Access audio, video, and images.

•  Setting—View and retrieve Bluetooth settings, ring tones, and other device preferences.

Android Native ContentProvider

Page 41: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 41 Fall 2013 CS 495/595 - App Development for Smart Devices

•  Android defines CONTENT_URI constants for all the providers that come with the platform.

Android Native ContentProvider

•  ContactsContract.CommonDataKinds.Phone.CONTENT_URI (content://com.android.contacts/data/phones)

•  Browser.BOOKMARKS_URI

(content://browser/bookmarks) •  MediaStore.Video.Media.EXTERNAL_CONTENT_URI

(content://media/external/video/media)

Classes section under : http://developer.android.com/reference/android/provider/package-summary.html

(if a provider, CONTENT_URI field exist)

Page 42: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 42 Fall 2013 CS 495/595 - App Development for Smart Devices

Page 43: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 43 Fall 2013 CS 495/595 - App Development for Smart Devices

• You need – URI

•  ContactsContract.Contacts.CONTENT_URI

– Names of data fields (result comes in table) •  ContactsContract.Contacts.DISPLAY_NAME

– Data types of those fields •  String

• Remember to modify the manifest file for permissions!

Querying Native Content Provider

To retrieve the contacts: <uses-permission android:name="android.permission.READ_CONTACTS"> </uses-permission>

Page 44: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 44 Fall 2013 CS 495/595 - App Development for Smart Devices

Query import android.provider.Contacts.People; import android.content.ContentUris; import android.net.Uri; import android.database.Cursor; // Use the ContentUris method to produce the // base URI for the contact with _ID == 23. // à ”content://com.android.contacts/people/23” Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23); // Alternatively, use the Uri method to produce the base URI. // It takes a string rather than an integer. // à ”content://com.android.contacts/people/23” Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23"); // Then query for this specific record: Cursor cur = managedQuery(myPerson, null, null, null, null);

For more information on URI handling functions: http://developer.android.com/reference/android/net/Uri.html

Page 45: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 45 Fall 2013 CS 495/595 - App Development for Smart Devices

Query import android.provider.Contacts.People; import android.database.Cursor; // Form an array specifying which columns to return. String[] projection = new String[] { People._ID, People._COUNT, People.NAME, People.NUMBER }; // Get the base URI for the People table in the Contacts content provider. Uri contacts = People.CONTENT_URI; // Make the query. Cursor managedCursor = managedQuery(contacts, projection, // Which columns to return null, // Which rows to return (all rows) null, // Selection arguments (none) // Put the results in ascending order by name People.NAME + " ASC");

Page 46: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 46 Fall 2013 CS 495/595 - App Development for Smart Devices

• Content Resolver •  getContentResolver().query(…) •  getContentResolver().insert(…) •  getContentResolver().update(…) •  getContentResolver().delete(…)

• Cursor cur = managedQuery(…) is equivalent to Cursor cur = getContentResolver().query(…); startManagingCursor(cur);

• Starting HoneyComb (API level 11) CursorLoader cl = new CursorLoader(this, …); Cursor cur = cl.loadInBackground()

Query

Page 47: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 47 Fall 2013 CS 495/595 - App Development for Smart Devices

Insert/Update/Delete

private void updateRecord(int recNo, String name) { //appending recNo, record to be updated Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, recNo); ContentValues values = new ContentValues(); values.put(People.NAME, name); getContentResolver().update(uri, values, null, null);

}

private void insertRecords(String name, String phoneNo) { ContentValues values = new ContentValues(); values.put(People.NAME, name); Uri uri = getContentResolver().insert(People.CONTENT_URI, values);

}

private void deleteRecords() { Uri uri = People.CONTENT_URI; getContentResolver().delete(uri, null, null);

}

Page 48: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 48 Fall 2013 CS 495/595 - App Development for Smart Devices

1.  Set up a system for storing the data •  e.g., SQLite using SQLiteOpenHelper

2.  Extend ContentProvider class to provide access: •  query()—Allows third-party applications to retrieve content. •  insert()—Allows third-party applications to insert content. •  update()—Allows third-party applications to update content. •  delete()—Allows third-party applications to delete content. •  getType()—Allows third-party applications to read each of URI

structures supported. •  onCreate()—Creates a database instance to help retrieve the content.

3. Declare the Content Provider in manifest

Implementing your own Content Provider

Page 49: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 49 Fall 2013 CS 495/595 - App Development for Smart Devices

Extend Content Provider

public class MyContentProvider extends ContentProvider { public static final String AUTHORITY = "edu.odu.phonenumber"; public static final Uri CONTENT_URI =

Uri.parse("content://"+ AUTHORITY + "/phones"); private MySQLDatabase mDB;

private static final int PHONES = 1; private static final int PHONES_ID = 2; private static final UriMatcher uriMatcher; static{

uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(AUTHORITY, “phones", PHONES); uriMatcher.addURI(AUTHORITY, “phones/#", PHONES_ID);

}

public boolean onCreate() { mDB = new MySQLDatabase(getContext()); return true; } … }

Page 50: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 50 Fall 2013 CS 495/595 - App Development for Smart Devices

Extend Content Provider public class MyContentProvider extends ContentProvider {

public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Cursor c=null; SQLiteDatabase db = mDB.getWritableDatabase(); switch (uriMatcher.match(uri)) { case PHONES: //get all phones records ... break; case PHONES_ID: //get a particular phone record … break; }

… }

public String getType(Uri uri) {...} public int delete(Uri uri, String selection, String[] selectionArgs) {...} public Uri insert(Uri uri, ContentValues values) {...} public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {...}

}

For more information on URI handling functions: http://developer.android.com/reference/android/net/Uri.html

Page 51: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 51 Fall 2013 CS 495/595 - App Development for Smart Devices

Manifest

<application android:icon="@drawable/icon" android:label="@string/app_name"> …

<provider android:name=".MyContentProvider" android:authorities=" edu.odu.phonenumber"></provider>

</application>

Page 52: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 52 CS 495/595 - App Development for Smart Devices Fall 2013

Project Ideas

Page 53: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 53 Fall 2013 CS 495/595 - App Development for Smart Devices

•  Security •  ODU Secure App

•  Localization •  Taking random pictures from your cell at home when it is on a table. Could you

locate the phone using the ceiling feature?

•  Medical/health/activity monitoring •  Parkin's disease detection

•  EEG Set

•  Transportation •  Detecting and identifying whether group of people are on the same transportation

unit/same side using correlation of accelerometer, gyro, …

•  Toll Tracking App.

Project’s Idea

Page 54: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 54 Fall 2013 CS 495/595 - App Development for Smart Devices

•  Education •  Interactive classroom

•  Misc •  Understanding Interface activities power consumption

•  Extension of MagnoTricoder

•  Wound Care App

•  Last Year Projects: •  http://www.cs.odu.edu/~nadeem/classes/cs495-F12/projects.htm

•  http://www.cs.odu.edu/~nadeem/classes/cs495-F11/projects.htm

Project’s Idea

Page 55: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 55 CS 495/595 - App Development for Smart Devices Fall 2013

Class Project Timeline

• Goal: obtain hands-on experience

• Semester-long research project to be done individually or in teams of two.

• Students will have the flexibility to either formulate their own project or choose from the ideas suggested by the instructor.

•  Timeline •  Team formation: Due – Sept. 27th, 2013 (team members + team name) •  Project Idea Selection: Due – Oct. 11th, 2013 (One page description) •  Project Proposal Draft: Due – Oct 21th, 2013 (one page proposal +

presentation slides) •  Project Status Update: Due – Nov 11th, 2013 (one page update +

presentation slides) •  Final Project Presentation: Due – Dec 2nd, 2013 (report + presnetation

slides + demo)

Page 56: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 56 CS 495/595 - App Development for Smart Devices Fall 2013

Questions?

Page 57: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 57 Fall 2013 CS 495/595 - App Development for Smart Devices

•  p168: Handling View Events •  p191: Displaying a Long List of Items using the ListView •  p197: Checking which Items are Selected •  p235 Creating the Menu Helper Methods •  p238: Displaying an Option Menu •  p240: Displaying a Context Menu •  p252: Saving Data Using the SharedPreferences Object •  p259: Retrieving and Modifying Preferences •  p263: Saving Data to Internal Storage •  p274: Creating the Database Helper Class •  p279: Adding Contacts to a Table •  p280: Retrieving All Contacts from a Table •  p281: Retrieving a Contact from a Table •  p282: Updating a Contact in a Table •  p283: Deleting a Contact from a Table •  p295: Using the Contacts Content Provider •  p305: Creating Your Own Content Provider

Recommended Assignment: Try It Out

(from previous class)

Database

Shared Preferences

Content Provider

Page 58: Lec #3: Files, Preferences, and Content Providernadeem/classes/cs495-F13/... · Tamer Nadeem Dept. of Computer Science Lec #3: Files, Preferences, and Content Provider. Page 2 Fall

Page 58 Fall 2013 CS 495/595 - App Development for Smart Devices

•  Assignment Tracker App •  Due Sunday Sep 29, 11:59pm

Assignment #2: Application Programming (ODUCS App)