2. » Content providers allow programs access to data
which is present on the device.
» A content provider manages access to a central
repository of data.
» They encapsulate the data from tables, and provide
mechanisms for defining data security and unified
usage.
» Content providers are the standard interface that
connects data in one process with code running in
another process.
3. Content Provider Intended Data
Browser Browser bookmarks, browser
history, etc.
CallLog Missed calls, call details, etc.
Contacts Contact details
MediaStore Media files such as audio, video
and images
Settings Device settings and preferences
4. » Irrespective of how the data is stored, Content
Providers give a uniform interface to access the data.
» Data is exposed as a simple table with rows and
columns where row is a record and column is a
particular data type with a specific meaning.
» Each record is identified by a unique _ID field which is
the key to the record.
» Each content provider exposes a unique URI that
identifies its data set uniquely. URI == table-name
5. » First we need to create a layout and activity class.
» In our layout we need to create a ListView.
» Create a cursor to query the phone database for
the contacts..
» Use an adaptor to send the results to the view for
displaying
6. » An application accesses the data from a content
provider with a ContentResolver client object.
» The ContentResolver methods provide the basic
"CRUD" (create, retrieve, update, and delete)
functions of persi
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection statement
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
7. » A content URI is a URI that identifies data in a
provider.
» Content URIs include the symbolic name of the
entire provider (its authority) and a name that
points to a table (a path).
» content://user_dictionary/words
8. » To retrieve data from a provider, your application
needs "read access permission" for the provider in
androidmanifest.xml.
» Construct the query
˃ A "projection" defines the columns that will be returned for each row
˃ Do a query and return a cursor object which holds the result returned from the
database
» Read the result with the cursor implementation
˃ you can iterate over the rows in the results
˃ determine the data type of each column
˃ get the data out of a column
˃ And more!
10. » Cursor is an interface that provides random read-write access
to the result of a database query from a content provider.
» A cursor is a collection of rows
» All field access methods are based on column number. You have
to convert column name to a column number first
» Random means (you can move forward and backwards)
» You can also find size / traverse result set easily.
Cursor cur;
for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()) {
//access methods
}
11. » Since a Cursor is a "list" of rows, a good way to
display the contents of a Cursor is to link it to
a ListView via an adaptor.
// Creates a new SimpleCursorAdapter
mCursorAdapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
R.layout.wordlistrow, // A layout in XML for one row in the ListView
mCursor, // The result from the query
mWordListColumns, // A string array of column names in the cursor
mWordListItems, // An integer array of view IDs in the row layout
0); // Flags (usually none are needed)
// Sets the adapter for the ListView
mWordList.setAdapter(mCursorAdapter);
12. Since our activity consists of a list, we can extend the class
public class MyActivity extends ListActivity
ListActivity to make life easier.
{
ListView lv;
Cursor Cursor1; lv is used to manage the Listview, note that since the layout contains only one listview,
the extend ListActivity is enough for the connection.
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); A projection is the specific columns of the
setContentView(R.layout.main); table that we want to query.
String [] projection = new String[] { Phone.DISPLAY_NAME,
Phone.NUMBER,
Phone._ID getContentResolver() – returns a ContentResolver object
}; from the activity class that can be used to query the
content databases with
Cursor1 = getContentResolver().query( query(projection, selection, selectionargs, sortorder)
Phone.CONTENT_URI,
projection,
null,
null, Phone.CONTENT_URI :
Phone.DISPLAY_NAME + " ASC"); (android.provider.ContactsContract.CommonDataKinds.Phone)
Points to the contact database location
startManagingCursor(Cursor1);
13. startManagingCursor(Cursor1); From and to are used to convert between the
result of the query in the cursor to the textview’s
String[] from = { in a list layout
Phone.DISPLAY_NAME,
Phone.NUMBER,
SimpleCursorAdapter maps columns
Phone._ID}; from a cursor to TextViews or
ImageViews defined in an XML file.
int[] to = {android.R.id.text1, android.R.id.text2}; Cursor1, from, to are the respective data
args
SimpleCursorAdapter listadapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
Cursor1, from, to );
setListAdapter(listadapter);
android.R.layout.simple_list_item_2 is an inbuilt
lv = getListView(); layout with 2 textviews for a list.
A custom XML layout in res/layout can be inserted
} // onCreate ends here
here too with the id names of the textveiws replaced
in the to variable.
14. […]
Get the cursor object and
cursor = managedQuery(EXTERNAL_CONTENT_URI, perform the query on it
proj, selection, arg, sort);
Find the listview view from
list = (ListView) findViewById(R.id.List01); the view
list.setAdapter(new N_Adapter(getApplicationContext(), cursor));
[..]
Use this function to bind the listview to an adaptor of
class N_Adapter..
The function is taking a constructor to this class as
arguments
15. public class N_Adapter extends BaseAdapter { This class extends BaseAdapter which is the base
private Context mContext; class for all adapter implementations
Cursor cursor;
public N_Adapter(Context c,Cursor m) { This constructor takes in the arguments passed to it
mContext = c; and returns the object to the setadapter method.
cursor = m;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position; These functions are required for the adapter to work
} properly within the android subsystem
public long getItemId(int position) {
return position;
}
16. This function performs
the binding between the
public View getView(int position, View convertView, ViewGroup parent) { cursor and the listview.
TextView tv;
View row; The view row is used to hold the xml file to place the
LayoutInflater inflater = getLayoutInflater(); listview’s contents in.
if (convertView == null) { convertView is in case the inflated view is being
row = inflater.inflate(android.R.layout.item, null); passed in as arguments, in this case – we don’t
} else want to inflate again..
row = convertView; android.R.layout.item -> xml file for the list
elements
tv = (TextView) row.findViewById(R.id.TextView01);
cursor.moveToPosition(position);
music_column_index = cursor .getColumnIndexOrThrow(People.DISPLAY_NAME);
id = cursor.getString(music_column_index);
Cursor is a class member initialized by the
tv.setText(id); argument to the constructor, these lines extract
return row; the data required and pass it to the textView
} element in the listview XML file.
}
17. » Create a large text white background contacts list.
» Attach an on click event to each list item and open
a new activity that shows that contact’s details
» Make an application that allows you to enter a
phrase and searches through the SMS messages
for all sms’s containing that text.
18. » Make a edittext view in a layout and load it in
activity.
» Make a button and bind an onclickhandler() to it
» When the button is clicked, load sms from the
content provider and search the contents for all
messages containing that word.
» Display all messages (one by one or in a listview as
per your choice)
19. » <uses-permission
android:name="android.permission.READ_SMS"></uses-permission>
» <uses-permission
android:name="android.permission.READ_CONTACTS"></uses-
permission>
» URI for sms content providers is as follows
» Inbox = "content://sms/inbox"
» Failed = "content://sms/failed"
» Queued = "content://sms/queued"
» Sent = "content://sms/sent"
» Draft = "content://sms/draft"
» Outbox = "content://sms/outbox"
» Undelivered = "content://sms/undelivered"
» All = "content://sms/all"
» Conversations = "content://sms/conversations"
21. » Uri uri = Uri.parse("content://sms/inbox");
» Cursor c= getContentResolver().query(uri, null,
null ,null,null);
» startManagingCursor(c)
22. body = new String[c.getCount()];
number = new String[c.getCount()];
if(c.moveToFirst()){
for(int i=0;i<c.getCount();i++){
body[i]= c.getString(c.getColumnIndexOrThrow("body")).toString();
number[i]=c.getString(c.getColumnIndexOrThrow("address")).toString();
c.moveToNext();
}
}
c.close();
23. » Understand the application and do proper
research online!
» This example has some concepts that you have to
figure out on your own.
» Use documentation, books provided and other
online resources to code the application.
» Ask help in online forums also!