use of android.content.ContentProviderOperation in project platform_frameworks_base by android.
the class TvInputManagerService method registerBroadcastReceivers.
private void registerBroadcastReceivers() {
PackageMonitor monitor = new PackageMonitor() {
private void buildTvInputList(String[] packages) {
synchronized (mLock) {
if (mCurrentUserId == getChangingUserId()) {
buildTvInputListLocked(mCurrentUserId, packages);
buildTvContentRatingSystemListLocked(mCurrentUserId);
}
}
}
@Override
public void onPackageUpdateFinished(String packageName, int uid) {
if (DEBUG)
Slog.d(TAG, "onPackageUpdateFinished(packageName=" + packageName + ")");
// This callback is invoked when the TV input is reinstalled.
// In this case, isReplacing() always returns true.
buildTvInputList(new String[] { packageName });
}
@Override
public void onPackagesAvailable(String[] packages) {
if (DEBUG) {
Slog.d(TAG, "onPackagesAvailable(packages=" + Arrays.toString(packages) + ")");
}
// available.
if (isReplacing()) {
buildTvInputList(packages);
}
}
@Override
public void onPackagesUnavailable(String[] packages) {
// unavailable.
if (DEBUG) {
Slog.d(TAG, "onPackagesUnavailable(packages=" + Arrays.toString(packages) + ")");
}
if (isReplacing()) {
buildTvInputList(packages);
}
}
@Override
public void onSomePackagesChanged() {
// the TV inputs.
if (DEBUG)
Slog.d(TAG, "onSomePackagesChanged()");
if (isReplacing()) {
if (DEBUG)
Slog.d(TAG, "Skipped building TV input list due to replacing");
// methods instead.
return;
}
buildTvInputList(null);
}
@Override
public boolean onPackageChanged(String packageName, int uid, String[] components) {
// the update can be handled in {@link #onSomePackagesChanged}.
return true;
}
@Override
public void onPackageRemoved(String packageName, int uid) {
synchronized (mLock) {
UserState userState = getOrCreateUserStateLocked(getChangingUserId());
if (!userState.packageSet.contains(packageName)) {
// Not a TV input package.
return;
}
}
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
String selection = TvContract.BaseTvColumns.COLUMN_PACKAGE_NAME + "=?";
String[] selectionArgs = { packageName };
operations.add(ContentProviderOperation.newDelete(TvContract.Channels.CONTENT_URI).withSelection(selection, selectionArgs).build());
operations.add(ContentProviderOperation.newDelete(TvContract.Programs.CONTENT_URI).withSelection(selection, selectionArgs).build());
operations.add(ContentProviderOperation.newDelete(TvContract.WatchedPrograms.CONTENT_URI).withSelection(selection, selectionArgs).build());
ContentProviderResult[] results = null;
try {
ContentResolver cr = getContentResolverForUser(getChangingUserId());
results = cr.applyBatch(TvContract.AUTHORITY, operations);
} catch (RemoteException | OperationApplicationException e) {
Slog.e(TAG, "error in applyBatch", e);
}
if (DEBUG) {
Slog.d(TAG, "onPackageRemoved(packageName=" + packageName + ", uid=" + uid + ")");
Slog.d(TAG, "results=" + results);
}
}
};
monitor.register(mContext, null, UserHandle.ALL, true);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
intentFilter.addAction(Intent.ACTION_USER_REMOVED);
mContext.registerReceiverAsUser(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_USER_SWITCHED.equals(action)) {
switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
} else if (Intent.ACTION_USER_REMOVED.equals(action)) {
removeUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
}
}
}, UserHandle.ALL, intentFilter, null, null);
}
use of android.content.ContentProviderOperation in project jpHolo by teusink.
the class ContactAccessorSdk5 method createNewContact.
/**
* Creates a new contact and stores it in the database
*
* @param contact the contact to be saved
* @param account the account to be saved under
*/
private String createNewContact(JSONObject contact, String accountType, String accountName) {
// Create a list of attributes to add to the contact database
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
//Add contact type
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName).build());
// Add name
try {
JSONObject name = contact.optJSONObject("name");
String displayName = contact.getString("displayName");
if (displayName != null || name != null) {
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, displayName).withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, getJsonString(name, "familyName")).withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, getJsonString(name, "middleName")).withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, getJsonString(name, "givenName")).withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, getJsonString(name, "honorificPrefix")).withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, getJsonString(name, "honorificSuffix")).build());
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get name object");
}
//Add phone numbers
JSONArray phones = null;
try {
phones = contact.getJSONArray("phoneNumbers");
if (phones != null) {
for (int i = 0; i < phones.length(); i++) {
JSONObject phone = (JSONObject) phones.get(i);
insertPhone(ops, phone);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get phone numbers");
}
// Add emails
JSONArray emails = null;
try {
emails = contact.getJSONArray("emails");
if (emails != null) {
for (int i = 0; i < emails.length(); i++) {
JSONObject email = (JSONObject) emails.get(i);
insertEmail(ops, email);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Add addresses
JSONArray addresses = null;
try {
addresses = contact.getJSONArray("addresses");
if (addresses != null) {
for (int i = 0; i < addresses.length(); i++) {
JSONObject address = (JSONObject) addresses.get(i);
insertAddress(ops, address);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get addresses");
}
// Add organizations
JSONArray organizations = null;
try {
organizations = contact.getJSONArray("organizations");
if (organizations != null) {
for (int i = 0; i < organizations.length(); i++) {
JSONObject org = (JSONObject) organizations.get(i);
insertOrganization(ops, org);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get organizations");
}
// Add IMs
JSONArray ims = null;
try {
ims = contact.getJSONArray("ims");
if (ims != null) {
for (int i = 0; i < ims.length(); i++) {
JSONObject im = (JSONObject) ims.get(i);
insertIm(ops, im);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Add note
String note = getJsonString(contact, "note");
if (note != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());
}
// Add nickname
String nickname = getJsonString(contact, "nickname");
if (nickname != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
}
// Add urls
JSONArray websites = null;
try {
websites = contact.getJSONArray("urls");
if (websites != null) {
for (int i = 0; i < websites.length(); i++) {
JSONObject website = (JSONObject) websites.get(i);
insertWebsite(ops, website);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get websites");
}
// Add birthday
String birthday = getJsonString(contact, "birthday");
if (birthday != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY).withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
}
// Add photos
JSONArray photos = null;
try {
photos = contact.getJSONArray("photos");
if (photos != null) {
for (int i = 0; i < photos.length(); i++) {
JSONObject photo = (JSONObject) photos.get(i);
insertPhoto(ops, photo);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get photos");
}
String newId = null;
//Add contact
try {
ContentProviderResult[] cpResults = mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
if (cpResults.length >= 0) {
newId = cpResults[0].uri.getLastPathSegment();
}
} catch (RemoteException e) {
Log.e(LOG_TAG, e.getMessage(), e);
} catch (OperationApplicationException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return newId;
}
use of android.content.ContentProviderOperation in project cordova-android-chromeview by thedracle.
the class ContactAccessorSdk5 method modifyContact.
/**
* Creates a new contact and stores it in the database
*
* @param id the raw contact id which is required for linking items to the contact
* @param contact the contact to be saved
* @param account the account to be saved under
*/
private String modifyContact(String id, JSONObject contact, String accountType, String accountName) {
// Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
// But not needed to update existing values.
int rawId = (new Integer(getJsonString(contact, "rawId"))).intValue();
// Create a list of attributes to add to the contact database
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
//Add contact type
ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName).build());
// Modify name
JSONObject name;
try {
String displayName = getJsonString(contact, "displayName");
name = contact.getJSONObject("name");
if (displayName != null || name != null) {
ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });
if (displayName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
}
String familyName = getJsonString(name, "familyName");
if (familyName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, familyName);
}
String middleName = getJsonString(name, "middleName");
if (middleName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middleName);
}
String givenName = getJsonString(name, "givenName");
if (givenName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, givenName);
}
String honorificPrefix = getJsonString(name, "honorificPrefix");
if (honorificPrefix != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, honorificPrefix);
}
String honorificSuffix = getJsonString(name, "honorificSuffix");
if (honorificSuffix != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, honorificSuffix);
}
ops.add(builder.build());
}
} catch (JSONException e1) {
Log.d(LOG_TAG, "Could not get name");
}
// Modify phone numbers
JSONArray phones = null;
try {
phones = contact.getJSONArray("phoneNumbers");
if (phones != null) {
// Delete all the phones
if (phones.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a phone
{
for (int i = 0; i < phones.length(); i++) {
JSONObject phone = (JSONObject) phones.get(i);
String phoneId = getJsonString(phone, "id");
// This is a new phone so do a DB insert
if (phoneId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing phone so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { phoneId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value")).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type"))).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get phone numbers");
}
// Modify emails
JSONArray emails = null;
try {
emails = contact.getJSONArray("emails");
if (emails != null) {
// Delete all the emails
if (emails.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a email
{
for (int i = 0; i < emails.length(); i++) {
JSONObject email = (JSONObject) emails.get(i);
String emailId = getJsonString(email, "id");
// This is a new email so do a DB insert
if (emailId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing email so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Email._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { emailId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value")).withValue(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type"))).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Modify addresses
JSONArray addresses = null;
try {
addresses = contact.getJSONArray("addresses");
if (addresses != null) {
// Delete all the addresses
if (addresses.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a address
{
for (int i = 0; i < addresses.length(); i++) {
JSONObject address = (JSONObject) addresses.get(i);
String addressId = getJsonString(address, "id");
// This is a new address so do a DB insert
if (addressId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country"));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing address so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { addressId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type"))).withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country")).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get addresses");
}
// Modify organizations
JSONArray organizations = null;
try {
organizations = contact.getJSONArray("organizations");
if (organizations != null) {
// Delete all the organizations
if (organizations.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a organization
{
for (int i = 0; i < organizations.length(); i++) {
JSONObject org = (JSONObject) organizations.get(i);
String orgId = getJsonString(org, "id");
// This is a new organization so do a DB insert
if (orgId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")));
contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"));
contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"));
contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title"));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing organization so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Organization._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { orgId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type"))).withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department")).withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name")).withValue(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title")).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get organizations");
}
// Modify IMs
JSONArray ims = null;
try {
ims = contact.getJSONArray("ims");
if (ims != null) {
// Delete all the ims
if (ims.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a im
{
for (int i = 0; i < ims.length(); i++) {
JSONObject im = (JSONObject) ims.get(i);
String imId = getJsonString(im, "id");
// This is a new IM so do a DB insert
if (imId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE, getImType(getJsonString(im, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing IM so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Im._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { imId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value")).withValue(ContactsContract.CommonDataKinds.Im.TYPE, getContactType(getJsonString(im, "type"))).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Modify note
String note = getJsonString(contact, "note");
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());
// Modify nickname
String nickname = getJsonString(contact, "nickname");
if (nickname != null) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
}
// Modify urls
JSONArray websites = null;
try {
websites = contact.getJSONArray("urls");
if (websites != null) {
// Delete all the websites
if (websites.length() == 0) {
Log.d(LOG_TAG, "This means we should be deleting all the phone numbers.");
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a website
{
for (int i = 0; i < websites.length(); i++) {
JSONObject website = (JSONObject) websites.get(i);
String websiteId = getJsonString(website, "id");
// This is a new website so do a DB insert
if (websiteId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing website so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Website._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { websiteId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value")).withValue(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type"))).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get websites");
}
// Modify birthday
String birthday = getJsonString(contact, "birthday");
if (birthday != null) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.CommonDataKinds.Event.TYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE, new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) }).withValue(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY).withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
}
// Modify photos
JSONArray photos = null;
try {
photos = contact.getJSONArray("photos");
if (photos != null) {
// Delete all the photos
if (photos.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a photo
{
for (int i = 0; i < photos.length(); i++) {
JSONObject photo = (JSONObject) photos.get(i);
String photoId = getJsonString(photo, "id");
byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
// This is a new photo so do a DB insert
if (photoId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing photo so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Photo._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { photoId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE }).withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1).withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get photos");
}
boolean retVal = true;
//Modify contact
try {
mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
Log.e(LOG_TAG, e.getMessage(), e);
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
retVal = false;
} catch (OperationApplicationException e) {
Log.e(LOG_TAG, e.getMessage(), e);
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
retVal = false;
}
// if the save was a success return the contact ID
if (retVal) {
return id;
} else {
return null;
}
}
use of android.content.ContentProviderOperation in project iosched by google.
the class SessionCalendarService method processAllSessionsCalendar.
/**
* Processes all sessions in the
* {@link com.google.samples.apps.iosched.provider.ScheduleProvider},
* adding or removing calendar events to/from the specified Google Calendar depending on whether
* a session is in the user's schedule or not.
*/
private ArrayList<ContentProviderOperation> processAllSessionsCalendar(ContentResolver resolver, final long calendarId) {
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
// Unable to find the Calendar associated with the user. Stop here.
if (calendarId == INVALID_CALENDAR_ID) {
return batch;
}
// Retrieves all sessions. For each session, add to Calendar if starred and attempt to
// remove from Calendar if unstarred.
Cursor cursor = resolver.query(ScheduleContract.Sessions.CONTENT_URI, SessionsQuery.PROJECTION, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
Uri uri = ScheduleContract.Sessions.buildSessionUri(Long.valueOf(cursor.getLong(0)).toString());
boolean isAddEvent = (cursor.getInt(SessionsQuery.SESSION_IN_MY_SCHEDULE) == 1);
if (isAddEvent) {
batch.addAll(processSessionCalendar(resolver, calendarId, isAddEvent, uri, cursor.getLong(SessionsQuery.SESSION_START), cursor.getLong(SessionsQuery.SESSION_END), cursor.getString(SessionsQuery.SESSION_TITLE), cursor.getString(SessionsQuery.ROOM_NAME)));
}
}
cursor.close();
}
return batch;
}
use of android.content.ContentProviderOperation in project iosched by google.
the class SessionCalendarService method processSessionCalendar.
/**
* Adds or removes a single session to/from the specified Google Calendar.
*/
private ArrayList<ContentProviderOperation> processSessionCalendar(final ContentResolver resolver, final long calendarId, final boolean isAddEvent, final Uri sessionUri, final long sessionBlockStart, final long sessionBlockEnd, final String sessionTitle, final String sessionRoom) {
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
// Unable to find the Calendar associated with the user or permissions were revoked.
if (calendarId == INVALID_CALENDAR_ID || !permissionsAlreadyGranted()) {
return batch;
}
final String calendarEventTitle = makeCalendarEventTitle(sessionTitle);
Cursor cursor;
ContentValues values = new ContentValues();
// Add Calendar event.
if (isAddEvent) {
if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) {
LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters.");
return batch;
}
// Check if the calendar event exists first. If it does, we don't want to add a
// duplicate one.
//noinspection MissingPermission
cursor = resolver.query(// URI
CalendarContract.Events.CONTENT_URI, // Projection
new String[] { CalendarContract.Events._ID }, // Selection
CalendarContract.Events.CALENDAR_ID + "=? and " + CalendarContract.Events.TITLE + "=? and " + CalendarContract.Events.DTSTART + ">=? and " + CalendarContract.Events.DTEND + "<=?", new String[] { // Selection args
Long.valueOf(calendarId).toString(), calendarEventTitle, Long.toString(Config.CONFERENCE_START_MILLIS), Long.toString(Config.CONFERENCE_END_MILLIS) }, null);
long newEventId = -1;
if (cursor != null && cursor.moveToFirst()) {
// Calendar event already exists for this session.
newEventId = cursor.getLong(0);
cursor.close();
// Data fix (workaround):
batch.add(ContentProviderOperation.newUpdate(CalendarContract.Events.CONTENT_URI).withValue(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID()).withSelection(CalendarContract.Events._ID + "=?", new String[] { Long.valueOf(newEventId).toString() }).build());
// End data fix.
} else {
// Calendar event doesn't exist, create it.
// NOTE: we can't use batch processing here because we need the result of
// the insert.
values.clear();
values.put(CalendarContract.Events.DTSTART, sessionBlockStart);
values.put(CalendarContract.Events.DTEND, sessionBlockEnd);
values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom);
values.put(CalendarContract.Events.TITLE, calendarEventTitle);
values.put(CalendarContract.Events.CALENDAR_ID, calendarId);
values.put(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID());
@SuppressWarnings("MissingPermission") Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values);
String eventId = eventUri.getLastPathSegment();
if (eventId == null) {
// Should be empty at this point
return batch;
}
newEventId = Long.valueOf(eventId);
// Since we're adding session reminder to system notification, we're not creating
// Calendar event reminders. If we were to create Calendar event reminders, this
// is how we would do it.
//values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId));
//values.put(CalendarContract.Reminders.MINUTES, 10);
//values.put(CalendarContract.Reminders.METHOD,
// CalendarContract.Reminders.METHOD_ALERT); // Or default?
//cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
//values.clear();
}
// Update the session in our own provider with the newly created calendar event ID.
values.clear();
values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId);
resolver.update(sessionUri, values, null, null);
} else {
// Remove Calendar event, if exists.
// Get the event calendar id.
cursor = resolver.query(sessionUri, new String[] { ScheduleContract.Sessions.SESSION_CAL_EVENT_ID }, null, null, null);
long calendarEventId = -1;
if (cursor != null && cursor.moveToFirst()) {
calendarEventId = cursor.getLong(0);
cursor.close();
}
// Try to remove the Calendar Event based on key. If successful, move on;
// otherwise, remove the event based on Event title.
int affectedRows = 0;
if (calendarEventId != -1) {
//noinspection MissingPermission
affectedRows = resolver.delete(CalendarContract.Events.CONTENT_URI, CalendarContract.Events._ID + "=?", new String[] { Long.valueOf(calendarEventId).toString() });
}
if (affectedRows == 0) {
//noinspection MissingPermission
resolver.delete(CalendarContract.Events.CONTENT_URI, String.format("%s=? and %s=? and %s=? and %s=?", CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND), new String[] { Long.valueOf(calendarId).toString(), calendarEventTitle, Long.valueOf(sessionBlockStart).toString(), Long.valueOf(sessionBlockEnd).toString() });
}
// Remove the session and calendar event association.
values.clear();
values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null);
resolver.update(sessionUri, values, null, null);
}
return batch;
}
Aggregations