Reputation: 21
At the moment I have content observer set up which lets me know when any change happens to the contact. How can I only query for the contacts that have been updated such as the name field or phone number field in android using java?
class ContactObserver extends ContentObserver {
public ContactObserver(Handler handler){
super(handler);
}
@Override
public void onChange(boolean selfChange){
contactChanged();
}
}
public void contactChanged(){
ContentResolver contentResolver = getContentResolver();
String[] PROJECTION = new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,PROJECTION,null,null,null);
JSONArray contactsArray = new JSONArray();
String name;
String number;
String id;
try{
if(cursor.moveToFirst()){
do {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
id = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
JSONObject contact = new JSONObject();
contact.put("id", id);
contact.put("name", name);
contact.put("number", number);
contactsArray.put(contact);
}while(cursor.moveToNext());
}
}
catch(JSONException ex){}
//System.out.println(contactsArray.toString());
getUpdatedContacts(contactsArray.toString(), pointer);
}
Upvotes: 0
Views: 66
Reputation: 495
Use this code inside contactChanged(), and for more details on Contacts Provider reference
// projection for the query
String[] projection = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP
};
// sort order for the query
String sortOrder = ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP + " DESC";
// Query the Contacts Provider for recently updated contacts
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
projection,
null,
null,
sortOrder
);
// Loop through the results and handle the recently updated contacts
if (cursor != null) {
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Long lastUpdated = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP));
// handle recently updated contacts here
}
cursor.close();
}
// Don't forget to unregister the ContentObserver.
Upvotes: 0