Mobile Application Development Selected Topics – CPIT 490

Slides:



Advertisements
Similar presentations
Programming with Android: Data management
Advertisements

 data/data-storage.html#pref data/data-storage.html#pref 
Android – CoNTENT PRoViders
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
SQLite in Mobile Apps by Dan Youberg. Overview Many well known applications and Internet browsers use SQLite due to its very small size (~250 Kb). Also.
CONTENT PROVIDER. Content Provider  A content provider makes a specific set of the application's data available to other applications => Share data to.
SQLLite and Java CS-328 Dick Steflik. SQLLite Embedded RDBMS ACID Compliant Size – about 257 Kbytes Not a client/server architecture –Accessed via function.
CS378 - Mobile Computing Persistence - SQLite. Databases RDBMS – relational data base management system Relational databases introduced by E. F. Codd.
Data Persistence in Android
Data Storage: Part 1 (Preferences)
SQLite Database. SQLite Public domain database – Advantages Small (about 150 KB) – Used on devices with limited resources Each database contained within.
CSE 486/586, Spring 2013 CSE 486/586 Distributed Systems Content Providers & Services.
© Keren Kalif Intro to Android Development Written by Keren Kalif, Edited by Liron Blecher Contains slides from Google I/O presentation.
ANDROID UI – FRAGMENTS. Fragment  An activity is a container for views  When you have a larger screen device than a phone –like a tablet it can look.
Favorite Twitter® Searches App Android How to Program © by Pearson Education, Inc. All Rights Reserved.
Lec 04 Content Providers Adapters CursorLoaders Advanced Debugging.
Content providers Accessing shared data in a uniform way 1Content providers.
Cosc 5/4730 Android Content Providers and Intents.
Data Storage: Part 4 (Content Providers). Content Providers Content providers allow the sharing of data between applications. Inter-process communication.
COMP 365 Android Development.  Manages access from a central database  Allows multiple applications to access the same data.
CS378 - Mobile Computing Persistence. Saving State We have already seen saving app state into a Bundle on orientation changes or when an app is killed.
Data Storage: Part 2 (File System). Internal Storage versus External Storage Internal storage − for private data –By default, files saved to the internal.
CSE 486/586, Spring 2012 CSE 486/586 Distributed Systems Recitation.
Nilesh Singh Local Data Storage option Android provides several options for you to save persistent application data. - Shared preferences - Creation.
Data persistence How to save data using SharedPreferences, Files, and SQLite database 1Data persistence.
Address Book App 1. Define styles   Specify a background for a TextView – res/drawable/textview_border.xml.
9 Persistence - SQLite CSNB544 Mobile Application Development Thanks to Utexas Austin.
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Android Boot Camp.
CS378 - Mobile Computing Persistence. Saving State We have already seen saving app state into a Bundle on orientation changes or when an app is killed.
Persistence Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.
Mobile Software Development ISCG 7424 Department of Computing UNITEC John Casey and Richard Rabeder SQLite and Permissions.
SQLite DB Storing Data in Android RAVI GAURAV PANDEY 1.
Android: “Dynamic” data and Preferences data.
Android - SQLite Database 12/10/2015. Introduction SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with.
SQlite. SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Android Boot Camp.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Address Book App 1 Fall 2014 CS7020: Game Design and Development.
David Sutton USING CONTENT PROVIDERS. TOPICS COVERED THIS WEEK  Persistence  Introduction to databases  Content providers  Cursors  Cursor adapters.
CHAPTER 9 File Storage Shared Preferences SQLite.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
The Ingredients of Android Applications. A simple application in a process In a classical programming environment, the OS would load the program code.
Data Storage in Android Димитър Н. Димитров. Why talk about data? Why not 3D graphics or network connectivity? Data as fundamental term in computer science.
Editing a Twitter search. Viewing search results in a browser.
Content Providers.
Data Persistence Chapter 9. Objectives Learn about data storage methods Understand use of Shared Preferences Understand file-based storage and the differences.
CS499 – Mobile Application Development
Making content providers
Content provider.
Android Content Providers & SQLite
Data Storage: Part 4 (Content Providers)
Content Providers And Content Resolvers
Android Application Data Storage 1.
SQLite in Android Landon Cox March 2, 2017.
Mobile Software Development for Android - I397
Android Application SQLite 1.
CS499 – Mobile Application Development
Mobile Application Development Chapter 5 [Persistent Data in Android]
Activities and Intents
Content Providers.
Mobile Computing With Android ACST Android Database Storage Part 2
CMPE419 Mobile Application Development
CMPE419 Mobile Application Development
Mobile Computing With Android ACST 4550 Android Database Storage
Android Developer Fundamentals V2
Mobile Programming Dr. Mohsin Ali Memon.
Mobile Programming Dr. Mohsin Ali Memon.
Preference Activity class
Presentation transcript:

Mobile Application Development Selected Topics – CPIT 490 Android Fundamentals Mobile Application Development Selected Topics – CPIT 490 22-Apr-17

Data Storage Data Storage Shared Preferences (a lightweight mechanism) Data Files SQLite Content Provider Saving Data Your options (most complex apps use all) Shared Preferences (just to store name-value pair like name, DOB, etc) Bundles Local files (to store ad-hoc data like RSS feed, note-taking, etc); External storage (if you need to share data with other applications) Local database (SQLite) Remote database Saving data is obviously essential

Saving UI State 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

Shared Preferences 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/<package name>_preferences.xml) Shared among application components running in the same application context   //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(); }

DDMS – File Explorer http://developer.android.com/guide/developing/debugging/ddms.html (Window > Open Perspective > Other... > DDMS)

Creating and Sharing Prefs public static String MY_PREFS = "<package_name>_preferences"; 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();

Retrieving Prefs public static String MY_PREFS = "MY_PREFS"; 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", ""); }

Preference Activity 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

Shared Preferences Create an xml file to indicate what to store <PreferenceScreen xmlns:android=”http://schemas.android.com/apk/res/android”> <PreferenceCategory android:title=”Category 1”> Provide the key for different preferences <CheckBoxPreference … android:key=”checkboxPref” /> Create an activity that extends the PreferenceActivity base class, and then call the addPreferencesFromResource() method to load the XML file containing the preferences: addPreferencesFromResource(R.xml.myapppreferences); The MODE_PRIVATE constant indicates that the preference file can only be opened by the application that created it Use getString() method to retrieve string preferences and use putString() method to update string preferences Change the default preference (net.learn2develop .<packagename>_preferences.xml> using PreferenceManager prefMgr = getPreferenceManager(); prefMgr.setSharedPreferencesName(“appPreferences”);

Preference Activity XML <?xml version="1.0" encoding="utf-8"?>   <?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>

Preference Activity Options CheckBoxPreference EditTextPreference ListPreference RingtonePreference

Preference Activity 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);

Using Prefs from Pref. Activity Recorded shared prefs are stored in Application Context. Therefore, available to any component: Activities Services BroadcastReceiver    Context context = getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // then Retrieve values using get<type> method

Prefs change listeners 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

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.

Shared Preferences – Summary Lightweight key-value pair storage General framework that allows you to save and retrieve persistent key-value pairs of primitive data types. Use it to save any primitive data: booleans, floats, ints, longs, and strings. Persist amongst user sessions getSharedPreferences() – Use this if you need multiple preferences files identified by name where you specify with the first parameter getPreferences() – Use this if you need only one preferences file for your Activity. Since this will be the only preferences file for your Activity, you don’t supply a name Get a SharedPreferences.Editor Call edit() Add values with methods (put<type>()) Commit new values with commit() Use SharedPreferences methods (get<type>()) to grab the values from your preferences Example: getBoolean(key, defaultvalue);

Bundles 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

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); }

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"); }

Saving/loading files Biggest decision: location Local vs Remote Internal vs External When you create a new AVD, you can emulate the existence of an SD card. Simply enter the size of the SD card that you want to emulate Alternatively, you can simulate the presence of an SD card in the Android emulator by creating a disk image first and then attaching it to the AVD. The mksdcard.exe utility (located in the tools folder of the Android SDK) enables you to create an ISO disk image Code is standard Java 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);

Saving/loading files // MODE_WORLD_READABLE constant means that the file is only readable FileOutputStream fOut = openFileOutput(“textfile.txt”, MODE_WORLD_READABLE); MODE_PRIVATE (the file can only be accessed by the application that created it), MODE_APPEND (for appending to an existing file), and MODE_WORLD_WRITEABLE (all other applications have write access to the file). Convert a character stream into a byte stream OutputStreamWriter osw = new OutputStreamWriter(fOut); Use write() to write to a file: osw.write(str); To ensure everything is written to the file: osw.flush(); Close the file using: osw.close();

Saving/loading files Read the file: FileInputStream fIn = openFileInput(“textfile.txt”); InputStreamReader isr = new InputStreamReader(fIn); To read from the file: char[] inputBuffer = new char[100]; String s = “”; int charRead; while ((charRead = isr.read(inputBuffer))>0) { //---convert the chars to a String--- String readString = String.copyValueOf(inputBuffer, 0, charRead); s += readString; inputBuffer = new char[100]; } Using DDMS (under File Explorer) in Eclipse, we could see /data/data/net.learn2develop.Files/files To copy a file from emulator or device to computer: adb pull <source path on emulator> To upload a file to emulator or device: adb push <filename> <destination path on emulator> To modify file permissions: adb shell and chmod

Saving/Loading files 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 SD Card Writing Permission (AndroidManifest.xml)   <uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE"> </uses-permission>

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()) if (!sdCard.canRead()) //for writing sdCard.canWrite()  return sdCard.toString(); }

SD Card storage getExternalStorageDirectory() method is used to get the full path to the external storage returns the “/sdcard” path for a real device, and “/mnt/sdcard” for an Android emulator Don’t hardcode the path of the SD card as different manufacturers can assign different path for the SD card

Static Resources You could add files to your package during design time This is done in res/raw folder Use the getResources() method (of the Activity class) to return a Resources object, and then use its openRawResource() method to open the file contained in the res/raw folder InputStream is = this.getResources().openRawResource(R.raw.textfile); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String str = null; try { while ((str = br.readLine()) != null) { Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show(); } is.close(); br.close(); } catch (IOException e) { e.printStackTrace(); }

SQLite 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. SQLite does not verify that the type written to each cell is of the defined type Each DB is private to Application that created it Data is stored at: /data/data/<package name>/databases/<db name> 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

Using SQLite Use a helper class called DBAdapter that creates, opens, closes, and uses a SQLite database 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() execSQL(String sql, [Object[] bindArgs]) – executes the SQL directly (not a SELECT/INSERT/UPDATE/DELETE) rawQuery(String sql, String[] selectionArgs) – runs provided SQL and returns a Cursor over result set query() – has many different parameters but returns a Cursor over result set If you want to e.g. CREATE TABLE that does not return values you can use execSQL(), if you want a Cursor as result use rawQuery() (=SELECT statements). If you want to execute something in database without concerning its output (e.g create/alter tables), then use execSQL, but if you are expecting some results in return against your query (e.g. select records) then use rawQuery

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); }

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);" ); } // SQLiteOpenHelper class is a helper class in Android to manage database creation and version management // The onCreate() method creates a new database if the required database is not present. // The onUpgrade() method is called when the database needs to be upgraded. // Using Cursor enables Android to more efficiently manage rows and columns as needed

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

Querying SQL SQL Select Syntax (see http://www.sqlite.org/lang.html) SQL-select statements are based on the following components    The first two lines are mandatory, the rest is optional.

Querying SQLite 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. To upgrade the database, change the DATABASE_VERSION constant to a value higher than the previous one

Querying SQLite – query() Android Simple Queries The signature of the Android’s simple query method is:   http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

Querying SQLite – Example 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.

Cursor – Example

SQLite Pre-create the database using tools like SQLite Database Browser: http://sourceforge.net/projects/sqlitebrowser/ A filename for files added to the assets folder must be in lowercase letters NOTE: For the SharedPreferences object (by default) and the SQLite database, the data is accessible only by the application that creates it. In other words, it is not shareable. If you need to share data among different applications, you need to create a content provider By default, SharedPreferences are not shareable. But changing the mode to “World Readable” or “World Writable”, you could make SharedPreferences as shareable among different applications.

SQL Creating a table: CREATE TABLE table (col1 type, col2 type, …) Inserting into a table: INSERT INTO table (col1, col2, …) VALUES (val1, val2,…) Updating a table: UPDATE table SET col2 = newVal2 WHERE col1 = val1 Deleting from a table: DELETE FROM table WHERE col1 = val1 Create a String array of result_columns for the columns of data you want to retrieve String[] cols = new String[] {col1, col2, …}; Create a cursor object that retrieves the result of the query Cursor cursor = db.query(table, cols, whereClause, selectionArgs, groupBy, having, orderBy) All are parameters for how to filter data

SQL query() returns a Cursor object Relevant Cursor functions getCount(): Returns the number of elements returned in Cursor moveToFirst(), moveToNext(): Moves between the rows in the Cursor getColumnIndexOrThrow(String col): Gets the index of the column for the parameter Display the data List<Object> Create a list of your stored objects ArrayAdapter<Object> Bind each object to an item layout

Content Provider 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 – consistent approach to add or delete or query or edit content

About Content Provider 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 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.

Android Native ContentProvider 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 Android defines CONTENT_URI constants for all the providers that come with the platform. 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) Browser.SEARCHES_URI CallLog.CONTENT_URI MediaStore.Images.Media.INTERNAL_CONTENT_URI MediaStore.Images.Media.EXTERNAL_CONTENT_URI Settings.CONTENT_URI Classes section under : http://developer.android.com/reference/android/provider/package-summary.html (if a provider, CONTENT_URI field exist)  

Android Native ContentProvider

Querying Native Content Provider 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! To retrieve the contacts: <uses-permission android:name="android.permission.READ_CONTACTS"> </uses-permission>

Content Provider The equivalent of Uri allContacts = Uri.parse(“content://contacts/people/1”); Is using predefined constant together with the withAppendedId() method of the ContentUris class: import android.content.ContentUris; ... Uri allContacts = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, 1); Remember to modify the manifest file for permissions!

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. Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI , "23"); // Then query for this specific record: Cursor cur = managedQuery(myPerson, null, null, null, null); // second parameter of managedQuery (third in CursorLoader class) is called as projectection. It indicates how many columns are returned by the query // third and fourth parameters (fourth and fifth in CursorLoader class) are for filtering // last parameter is for sorting For more information on URI handling functions: http://developer.android.com/reference/android/net/Uri.html

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. // managedQuery is deprecated 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");

Query Instead of managedQuery() use Content Resolver 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() The CursorLoader class (only available beginning with Android API level 11 and later) performs the cursor query on a background thread and hence does not block the application UI

Insert/Update/Delete 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 updateRecord(int recNo, String name) { //appending recNo, record to be updated Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, recNo); values.put(People.NAME, name); getContentResolver().update(uri, values, null, null); private void deleteRecords(){ Uri uri = People.CONTENT_URI; getContentResolver().delete(uri, null, null);} The SimpleCursorAdapter object maps a cursor to TextViews (or ImageViews) defined in your XML file (main.xml).

Content Provider SimpleCursorAdapter constructor has an additional argument from Honeycomb and later //---Honeycomb and later--- adapter = new SimpleCursorAdapter(this, R.layout.main, c, columns, views, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); In AndroidManifest.xml, appropriate permission to access the Contacts of the mobile is required <uses-permission android:name="android.permission.READ_CONTACTS"/>

Implementing your own Content Provider Set up a system for storing the data (storage can be on a file or database or using a webservice) e.g., SQLite using SQLiteOpenHelper; you could refer to the database creation and update code to do similar things here 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. Declare the Content Provider in manifest

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;

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 } 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

Extend Content Provider //---add a book to the Content Provider --- ContentValues values = new ContentValues(); values.put(BooksProvider.TITLE, ((EditText) findViewById(R.id.txtTitle)).getText().toString()); Uri uri = getContentResolver().insert(BooksProvider.CONTENT_URI, values); // update a book ContentValues editedValues = new ContentValues(); editedValues.put(BooksProvider.TITLE, “Android Tips and Tricks”); getContentResolver().update(Uri.parse(“content://net.learn2develop.provider.Books/books/2”),editedValues, null, null); // Based on book ID //---delete a title based on book ID--- getContentResolver().delete(Uri.parse(“content://net.learn2develop.provider.Books/books/2”),null, null); //---delete all titles--- getContentResolver().delete(Uri.parse(“content://net.learn2develop.provider.Books/books”), null, null);

Manifest file update <application android:icon="@drawable/icon" android:label="@string/app_name"> <provider android:name=".MyContentProvider" android:authorities=" edu.odu.phonenumber"></provider> </application>

Recommendations to try (Menus from previous class) p235 Creating the Menu Helper Methods; p238: Displaying an Option Menu p240: Displaying a Context Menu Shared Preferences p252: Saving Data Using the SharedPreferences Object p259: Retrieving and Modifying Preferences p263: Saving Data to Internal Storage Database 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 Content Provider p295: Using the Contacts Content Provider p305: Creating Your Own Content Provider

References App Development for Smart Devices http://www.cs.odu.edu/~cs495/