Interactive Powerpoint_How to Master effective communication
5. content providers
1. Content Providers.
Step 1. Create a new Android Project of blank Activity.
Step 2. Add the following code to your
layout/layout_activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/contactview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Step3.
Access to thecontact ContentProvider requires a certain permission, as not all
applications should haveaccess to thecontact information. Open
the AndroidManifest.xml file, and select thePermissions tab. On that tab click
the Add button, and select the Uses Permission. From thedrop-down list select
the android.permission.READ_CONTACTS entry
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
Step 4. Add the following code on the“oncreate” method of your activity
TextView contactView = (TextView)
findViewById(R.id.contactview);
2. Step5. Addthe followingfunction.
private void getContacts() {
// Check the SDK version and whether the permission is already granted or not.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.READ_CONTACTS) !=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 100);
//After this point you wait for callback in onRequestPermissionsResult(int,
String[], int[]) overriden method
} else {
// Android version is lesser than 6.0 or the permission is already granted.
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
// display in the list view
contactView.setText(name);
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " =
?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
}
}
}
}
}
6. Use ListViewinsteadof TextViewto displaycontacts