Manoj Fegde
Manoj Fegde

Reputation: 4761

Android: Insert/Update/Delete contact

I am developing an application in which I list the device contacts, and perform some manipulation with them. I listen to contact changes as described in the following links: Link 1, Link 2

My code is as follows:

public class ContactService extends Service {
private int mContactCount;
Cursor cursor = null;
private int contactStateCheckingFlag=0;
static ContentResolver mContentResolver = null;

public static final String AUTHORITY = "com.example.contacts";
public static final String ACCOUNT_TYPE = "com.example.myapplication.account";
public static final String ACCOUNT = "myapplication";    
Account mAccount;

Bundle settingsBundle;    
int i=0;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();// Get contact count at start of service
    mContactCount = getContactCount();

    this.getContentResolver().registerContentObserver(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, true, mObserver);
    Cursor curval =  getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, null, null, null);

    if (curval != null && curval.getCount() > 0) {
        curval.getCount();
    }
    curval.close();
}

private int getContactCount() {
    try {
        cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null,null);
        if (cursor != null) {
            return cursor.getCount();
        } else {
            cursor.close();
            return 0;
        }
    } catch (Exception ignore) {
    } finally {
        cursor.close();
    }       
    return 0;
}

private ContentObserver mObserver = new ContentObserver(new Handler()) {        
    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);         
        new ContactServiceAsyncClass().execute();           
    }       
};

private class ContactServiceAsyncClass extends AsyncTask<Void, Void, Void> {
    ArrayList<Integer> arrayListContactID = new ArrayList<Integer>();
    @Override
    protected void onPreExecute() {
        super.onPreExecute();           
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Get the current count of contacts
        int currentCount = getContactCount();

        // Add New Contact
        if (currentCount > mContactCount){
            Cursor contactCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

            if (contactCursor.getCount()<=0) {
                Log.d("Contact Cursor count"," is zero");
            }else {
                Log.d("Contact Cursor count", " > 0");                  
                // Fetch all contact ID from cursor
                if(contactCursor.moveToFirst()){
                    do {    
                        int contactID = contactCursor.getInt(contactCursor.getColumnIndex(ContactsContract.Data._ID));
                        arrayListContactID.add(contactID);
                    } while (contactCursor.moveToNext());
                }                   
                // Sort the array list having all contact ID
                Collections.sort(arrayListContactID);
                Integer maxID=Collections.max(arrayListContactID);
                Log.d("maxID", ""+maxID);                   
                // Get details of new added contact from contact id
                String whereName = ContactsContract.Data._ID + " = ?";// Where condition
                String[] whereNameParams = new String[] { ""+maxID}; // Pass maxID
                Cursor cursorNewContact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, whereName, whereNameParams, null);

                if(cursorNewContact.getCount()<=0){
                }else {
                    if(cursorNewContact.moveToFirst()){
                        do{
                            // Fetch new added contact details
                        } while(cursorNewContact.moveToNext());
                    }
                }
                cursorNewContact.close();
            }   
            contactCursor.close();
        } else if(currentCount < mContactCount){
            // Delete Contact/
            // CONTACT DELETED.
        } else if(currentCount == mContactCount){
            // Update Contact1
        }               
        mContactCount = currentCount;
        return null;
    }   

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}   
}

I am able to fetch new added contact. The question is how to delete and update contact? How to know which contact is deleted and updated, as the contact change broadcast doesn't specify the id of the contact that changed?

Please provide your valuable suggestions and guide me in detail.

Thank you.

Upvotes: 0

Views: 1578

Answers (1)

stacktry
stacktry

Reputation: 322

For delete operation,

1.First you store the previous list of contacts id in local database.

for example: you added contact id`s are 123,124,125.

Now we assume your last added contact(125) was deleted.

How we find it?.

simple first get the list of old contact list. and compare with current contact list.

If old contact list element not in the new list, that contact is deleted from phone.

Note: If delete operation complete, you need to update the contact id`s into DB.

For Update operation,

1.Use VERSION flag for indicating any changes in your contact.

2.VERSION default value is 1. if you modify the contacts,it automatically increase to 2.

3.So you need to store old version value in your local DB. and compare the version value increase or not. If increase the VERSION value you need to update this contact.

Refer the official link,

https://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html

For complete project,

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/4.0.4_r2.1/com/android/exchange/adapter/ContactsSyncAdapter.java?av=f

Upvotes: 1

Related Questions