Skip to main content

Content Provider Example(View Contacts,Add Contacts,Delete Contacts,Update Contacts)


This is the example of content provider.This example shows how to view ,add,modify and delete contacts.

ContentProvider_Demo.java


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 ContentProvider_Demo extends Activity {





/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);



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(ContentProvider_Demo.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(ContentProvider_Demo.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(ContentProvider_Demo.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(ContentProvider_Demo.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(ContentProvider_Demo.this, "Deleted the contact with name '" + name +"'", Toast.LENGTH_SHORT).show();



}

}

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"

>

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

string.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="hello"> Here is the contacts list</string>

<string name="app_name">ContentProvider_Demo</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>

manifest.xml

<?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.ContentProvider_Demo">

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name="com.example.contentprovidernewexample.ContentProvider_Demo"

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>

Comments

Popular posts from this blog

Custom camera using SurfaceView android with autofocus & auto lights & more

Custom camera using SurfaceView android with autofocus & auto lights & much more /**  * @author Tatyabhau Chavan  *  */ public class Preview extends SurfaceView implements SurfaceHolder.Callback {     private SurfaceHolder mHolder;     private Camera mCamera;     public Camera.Parameters mParameters;     private byte[] mBuffer;     private Activity mActivity;     // this constructor used when requested as an XML resource     public Preview(Context context, AttributeSet attrs) {         super(context, attrs);         init();     }     public Preview(Context context) {         super(context);         init();     }     public Camera getCamera() {        ...

Bitmap scalling and cropping from center

How to Bitmap scalling and cropping from center? public class ScalingUtilities {     /**      * Utility function for decoding an image resource. The decoded bitmap will      * be optimized for further scaling to the requested destination dimensions      * and scaling logic.      *      * @param res      *            The resources object containing the image data      * @param resId      *            The resource id of the image data      * @param dstWidth      *            Width of destination area      * @param dstHeight      *     ...

Improving Layout Performance

Improving Layout Performance Layouts are a key part of Android applications that directly affect the user experience. If implemented poorly, your layout can lead to a memory hungry application with slow UIs. The Android SDK includes tools to help you identify problems in your layout performance, which when combined the lessons here, you will be able to implement smooth scrolling interfaces with a minimum memory footprint. Lessons Optimizing Layout Hierarchies In the same way a complex web page can slow down load time, your layout hierarchy if too complex can also cause performance problems. This lesson shows how you can use SDK tools to inspect your layout and discover performance bottlenecks. Re-using Layouts with <include/> If your application UI repeats certain layout constructs in multiple places, this lesson shows you how to create efficient, re-usable layout constructs, then include them in the appropriate UI layouts. Loading Views On Demand Be...