Content Provider New Example In Android Programming

Description:
This example will show you how to handle content provider.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it ContentProviderNewExample.

2.) Write following into layout/contentprovidernewexample.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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:text="@string/viewButton"
android:id="@+id/viewButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
</Button>
<Button
android:text="@string/createButton"
android:id="@+id/createButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
</Button>
<Button
android:text="@string/updateButton"
android:id="@+id/updateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
</Button>
<Button
android:text="@string/deleteButton"
android:id="@+id/deleteButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
</Button>
</LinearLayout>

 

 

3.) Write following into values/string.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">This example is the working of a native content provider - here the contacts list</string>
<string name="app_name">ContentProviderNewExample</string>
<string name="viewButton">View Contacts</string>
<string name="createButton">Add Contact</string>
<string name="updateButton">Modify Contact</string>
<string name="deleteButton">Delete Contact</string>
</resources>

 

 

4.) Write following into your manifest file:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" package="com.example.contentprovidernewexample">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name="com.example.contentprovidernewexample.ContentProviderNewExample"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>
</manifest>

 

 

5.) Run for output.

Steps:

1.) Create a project named ContentProviderNewExample and set the information as stated in the image.

Build Target: Android 4.2
Application Name: ContentProviderNewExample
Package Name: com.example.ContentProviderNewExample
Activity Name: ContentProviderNewExample
Min SDK Version: 4.2

2.) Open ContentProviderNewExample.java file and write following code there:

 

package com.example.contentprovidernewexample;

import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.database.Cursor;

import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ContentProviderNewExample extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contentprovidernewexample);

Button view = (Button)findViewById(R.id.viewButton);
Button add = (Button)findViewById(R.id.createButton);
Button modify = (Button)findViewById(R.id.updateButton);
Button delete = (Button)findViewById(R.id.deleteButton);

view.setOnClickListener(new OnClickListener() {
public void onClick(View v){
displayContacts();
Log.i("NativeContentProvider", "Completed Displaying Contact list");
}
});

add.setOnClickListener(new OnClickListener() {
public void onClick(View v){
createContact("Example Name", "123456789");
Log.i("NativeContentProvider", "Created a new contact, of course hard-coded");
}
});

modify.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateContact("Example Name", "987604321");
Log.i("NativeContentProvider", "Completed updating the email id, if applicable");
}
});

delete.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
deleteContact("Example Name");
Log.i("NativeContentProvider", "Deleted the just created contact");
}
});
}

private void displayContacts() {

ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.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));
if (Integer.parseInt(cur.getString(
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));
Toast.makeText(ContentProviderNewExample.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
}
pCur.close();
}
}
}
}

private void createContact(String name, String phone) {
ContentResolver cr = getContentResolver();

Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);

if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String existName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (existName.contains(name)) {
Toast.makeText(ContentProviderNewExample.this,"The contact name: " + name + " already exists", Toast.LENGTH_SHORT).show();
return;
}
}
}

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "accountname@gmail.com")
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "com.google")
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
.build());

try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Toast.makeText(ContentProviderNewExample.this, "Created a new contact with name: " + name + " and Phone No: " + phone, Toast.LENGTH_SHORT).show();

}

private void updateContact(String name, String phone) {
ContentResolver cr = getContentResolver();

String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ? AND " +
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";
String[] params = new String[] {name,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)};

Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI, null, where, params, null);

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

if ( (null == phoneCur) ) {
createContact(name, phone);
} else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.Phone.DATA, phone)
.build());
}

phoneCur.close();

try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Toast.makeText(ContentProviderNewExample.this, "Updated the phone number of 'Example Name' to: " + phone, Toast.LENGTH_SHORT).show();
}

private void deleteContact(String name) {

ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
String[] params = new String[] {name};

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
.withSelection(where, params)
.build());
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Toast.makeText(ContentProviderNewExample.this, "Deleted the contact with name '" + name +"'", Toast.LENGTH_SHORT).show();

}
}

 

 

3.) Compile and build the project.

Output

Leave a Comment: