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

Volley for client and server interaction (Android)

Volley provides client and server interaction with QUEUE basis, each and every request process separately, we can cancel our request from QUEUE. HERE is a code sample for Volley with json request format. GenerateRequest.java -------------------------------------------------------------------- package com.entrata.maintenance.network_communication.networkutils; import android.content.Context; import com.android.volley.AuthFailureError; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.entrata.maintenance.application.ERPUserDefaults; import com.entrata.maintenance.network_communication.networkconstant.NetworkConstant; import com.entrata.maintenance.network_communication.networkexception.Error; import com.entrata.maintenance.network_communication.networkutil.SubdomainChange; import com.entrata.maintenance.utils.Logger; import com.google.gson.Gson; import org.json.JSONException; import org.js...
Java Code Examples for javax.net.ssl.HttpsURLConnection The following code examples are extracted from open source projects. You can click to vote up the examples you like. Your votes will be used in an intelligent system to get more and better code examples. Thanks for your votes! Code Example 1:   9  From project ADFS , under directory /adfs-hdfs-project/adfs-hdfs/src/main/java/org/apache/hadoop/hdfs/ . Source HsftpFileSystem.java @Override protected HttpURLConnection openConnection ( String path , String query ) throws IOException { query = addDelegationTokenParam ( query ); final URL url = new URL ( "https" , nnAddr . getHostName (), nnAddr . getPort (), path + '?' + query ); HttpsURLConnection conn =( HttpsURLConnection ) url . openConnection (); conn . setHostnameVerifier ( new DummyHostnameVerifier ()); return ( HttpURLConnection ) conn ; } Code Example 2:  ...

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