Top Banner
Content Providers & Intents Workshop India
23

05 content providers - Android

May 10, 2015

Download

Education

Wingston

This ppt provides an introduc
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 05   content providers - Android

Content Providers & Intents

Workshop India

Page 2: 05   content providers - Android

What are content providers?» 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.

Page 3: 05   content providers - Android

Content Providers available

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

Page 4: 05   content providers - Android

How they work» 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

Page 5: 05   content providers - Android

Lets display contacts» 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

Page 6: 05   content providers - Android

Reading a content provider» 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 resultsmCursor = 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

Page 7: 05   content providers - Android

Content URI» 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

Page 8: 05   content providers - Android

Retrieving Data» 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!

Page 9: 05   content providers - Android

res/layout/main.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent"/></LinearLayout>

This would create a listView of id list in the layout.

Page 10: 05   content providers - Android

Cursors & Content Providers» 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 }

Page 11: 05   content providers - Android

Linking cursor to a list view» 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 SimpleCursorAdaptermCursorAdapter = 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 ListViewmWordList.setAdapter(mCursorAdapter);

Page 12: 05   content providers - Android

Working with content providerspublic class MyActivity extends ListActivity{ ListView lv; Cursor Cursor1;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

String [] projection = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER, Phone._ID };

Cursor1 = getContentResolver().query( Phone.CONTENT_URI, projection, null, null, Phone.DISPLAY_NAME + " ASC");

startManagingCursor(Cursor1);

Since our activity consists of a list, we can extend the class ListActivity to make life easier.

lv is used to manage the Listview, note that since the layout contains only one listview, the extend ListActivity is enough for the connection.

A projection is the specific columns of the table that we want to query.

getContentResolver() – returns a ContentResolver object from the activity class that can be used to query the content databases with query(projection, selection, selectionargs, sortorder)

Phone.CONTENT_URI : (android.provider.ContactsContract.CommonDataKinds.Phone)Points to the contact database location

Page 13: 05   content providers - Android

CursorAdaptersstartManagingCursor(Cursor1);

String[] from = { Phone.DISPLAY_NAME, Phone.NUMBER,

Phone._ID};

int[] to = {android.R.id.text1, android.R.id.text2};

SimpleCursorAdapter listadapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2,

Cursor1, from, to );

setListAdapter(listadapter);

lv = getListView();

} // onCreate ends here

From and to are used to convert between the result of the query in the cursor to the textview’s in a list layout

SimpleCursorAdapter maps columns from a cursor to TextViews or ImageViews defined in an XML file.Cursor1, from, to are the respective data args

android.R.layout.simple_list_item_2 is an inbuilt layout with 2 textviews for a list.

A custom XML layout in res/layout can be inserted here too with the id names of the textveiws replaced in the to variable.

Page 14: 05   content providers - Android

Writing the adapter if needed[…]

cursor = managedQuery(EXTERNAL_CONTENT_URI, proj, selection, arg, sort);

list = (ListView) findViewById(R.id.List01);

list.setAdapter(new N_Adapter(getApplicationContext(), cursor));

[..]

Get the cursor object and perform the query on it

Find the listview view from the view

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

Page 15: 05   content providers - Android

Create the N_Adapter classpublic class N_Adapter extends BaseAdapter { private Context mContext; Cursor cursor;

public N_Adapter(Context c,Cursor m) { mContext = c; cursor = m; }

public int getCount() { return count; }

public Object getItem(int position) { return position; }

public long getItemId(int position) { return position; }

This class extends BaseAdapter which is the base class for all adapter implementations

This constructor takes in the arguments passed to it and returns the object to the setadapter method.

These functions are required for the adapter to work properly within the android subsystem

Page 16: 05   content providers - Android

The getView function public View getView(int position, View convertView, ViewGroup parent) { TextView tv; View row; LayoutInflater inflater = getLayoutInflater(); if (convertView == null) { row = inflater.inflate(android.R.layout.item, null); } else row = convertView;

tv = (TextView) row.findViewById(R.id.TextView01);

cursor.moveToPosition(position); music_column_index = cursor .getColumnIndexOrThrow(People.DISPLAY_NAME); id = cursor.getString(music_column_index);

tv.setText(id); return row; } }

This function performs the binding between the cursor and the listview.

The view row is used to hold the xml file to place the listview’s contents in.

convertView is in case the inflated view is being passed in as arguments, in this case – we don’t want to inflate again..android.R.layout.item -> xml file for the list elements

Cursor is a class member initialized by the argument to the constructor, these lines extract the data required and pass it to the textView element in the listview XML file.

Page 17: 05   content providers - Android

Exercise – Reading SMS» 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.

Page 18: 05   content providers - Android

Framework» 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)

Page 19: 05   content providers - Android

For sms» <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"

Page 20: 05   content providers - Android

Cursor columns available» addressCol= mCurSms.getColumnIndex("address"); » personCol= mCurSms.getColumnIndex("person"); » dateCol = mCurSms.getColumnIndex("date"); » protocolCol= mCurSms.getColumnIndex("protocol"); » readCol = mCurSms.getColumnIndex("read"); » statusCol = mCurSms.getColumnIndex("status"); » typeCol = mCurSms.getColumnIndex("type"); » subjectCol = mCurSms.getColumnIndex("subject"); » bodyCol = mCurSms.getColumnIndex("body");

Page 21: 05   content providers - Android

Eg: opening a cursor

» Uri uri = Uri.parse("content://sms/inbox");

» Cursor c= getContentResolver().query(uri, null, null ,null,null);

» startManagingCursor(c)

Page 22: 05   content providers - Android

Iterating through SMS’s

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

Page 23: 05   content providers - Android

Use online references » 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!