use of com.android.contacts.common.model.RawContactDelta in project packages_apps_Contacts by AOKP.
the class ConfirmAddDetailActivity method addEditableRawContact.
/**
* Create an {@link RawContactDelta} for a raw_contact on the first editable account found, and add
* to the list. Also copy the structured name from an existing (read-only) raw_contact to the
* new one, if any of the read-only contacts has a name.
*/
private static RawContactDelta addEditableRawContact(Context context, RawContactDeltaList entityDeltaList) {
// First, see if there's an editable account.
final AccountTypeManager accounts = AccountTypeManager.getInstance(context);
final List<AccountWithDataSet> editableAccounts = accounts.getAccounts(true);
if (editableAccounts.size() == 0) {
// No editable account type found. The dialog will be read-only mode.
return null;
}
final AccountWithDataSet editableAccount = editableAccounts.get(0);
final AccountType accountType = accounts.getAccountType(editableAccount.type, editableAccount.dataSet);
// Create a new RawContactDelta for the new raw_contact.
final RawContact rawContact = new RawContact();
rawContact.setAccount(editableAccount);
final RawContactDelta entityDelta = new RawContactDelta(ValuesDelta.fromAfter(rawContact.getValues()));
// Then, copy the structure name from an existing (read-only) raw_contact.
for (RawContactDelta entity : entityDeltaList) {
final ArrayList<ValuesDelta> readOnlyNames = entity.getMimeEntries(StructuredName.CONTENT_ITEM_TYPE);
if ((readOnlyNames != null) && (readOnlyNames.size() > 0)) {
final ValuesDelta readOnlyName = readOnlyNames.get(0);
final ValuesDelta newName = RawContactModifier.ensureKindExists(entityDelta, accountType, StructuredName.CONTENT_ITEM_TYPE);
// Copy all the data fields.
newName.copyStructuredNameFieldsFrom(readOnlyName);
break;
}
}
// Add the new RawContactDelta to the list.
entityDeltaList.add(entityDelta);
return entityDelta;
}
use of com.android.contacts.common.model.RawContactDelta in project packages_apps_Contacts by AOKP.
the class ContactSaveService method saveContact.
private void saveContact(Intent intent) {
RawContactDeltaList state = intent.getParcelableExtra(EXTRA_CONTACT_STATE);
boolean isProfile = intent.getBooleanExtra(EXTRA_SAVE_IS_PROFILE, false);
Bundle updatedPhotos = intent.getParcelableExtra(EXTRA_UPDATED_PHOTOS);
if (state == null) {
Log.e(TAG, "Invalid arguments for saveContact request");
return;
}
int saveMode = intent.getIntExtra(EXTRA_SAVE_MODE, -1);
// Trim any empty fields, and RawContacts, before persisting
final AccountTypeManager accountTypes = AccountTypeManager.getInstance(this);
RawContactModifier.trimEmpty(state, accountTypes);
Uri lookupUri = null;
final ContentResolver resolver = getContentResolver();
boolean succeeded = false;
// Keep track of the id of a newly raw-contact (if any... there can be at most one).
long insertedRawContactId = -1;
// Attempt to persist changes
Integer result = RESULT_FAILURE;
ArrayList<Long> rawContactsList = new ArrayList<Long>();
boolean isCardOperation = false;
for (int i = 0; i < state.size(); i++) {
final RawContactDelta entity = state.get(i);
final String accountType = entity.getValues().getAsString(RawContacts.ACCOUNT_TYPE);
final String accountName = entity.getValues().getAsString(RawContacts.ACCOUNT_NAME);
rawContactsList.add(entity.getRawContactId());
if (accountType != null && ExchangeAccountType.isExchangeType(accountType))
removeDisplayName(entity);
final int subscription = MoreContactUtils.getSubscription(accountType, accountName);
isCardOperation = (subscription != SubscriptionManager.INVALID_SUBSCRIPTION_ID) ? true : false;
if (isCardOperation) {
result = doSaveToSimCard(entity, resolver, subscription);
Log.d(TAG, "doSaveToSimCard result is " + result);
}
}
int tries = 0;
while (tries++ < PERSIST_TRIES) {
if (result == RESULT_SUCCESS || result == RESULT_FAILURE) {
try {
// Build operations and try applying
final ArrayList<CPOWrapper> diffWrapper = state.buildDiffWrapper();
final ArrayList<ContentProviderOperation> diff = Lists.newArrayList();
for (CPOWrapper cpoWrapper : diffWrapper) {
diff.add(cpoWrapper.getOperation());
}
if (DEBUG) {
Log.v(TAG, "Content Provider Operations:");
for (ContentProviderOperation operation : diff) {
Log.v(TAG, operation.toString());
}
}
int numberProcessed = 0;
boolean batchFailed = false;
final ContentProviderResult[] results = new ContentProviderResult[diff.size()];
while (numberProcessed < diff.size()) {
final int subsetCount = applyDiffSubset(diff, numberProcessed, results, resolver);
if (subsetCount == -1) {
Log.w(TAG, "Resolver.applyBatch failed in saveContacts");
batchFailed = true;
break;
} else {
numberProcessed += subsetCount;
}
}
if (batchFailed) {
// Retry save
continue;
}
final long rawContactId = getRawContactId(state, diffWrapper, results);
if (rawContactId == -1) {
throw new IllegalStateException("Could not determine RawContact ID after save");
}
// We don't have to check to see if the value is still -1. If we reach here,
// the previous loop iteration didn't succeed, so any ID that we obtained is bogus.
insertedRawContactId = getInsertedRawContactId(diffWrapper, results);
if (isProfile) {
// Since the profile supports local raw contacts, which may have been completely
// removed if all information was removed, we need to do a special query to
// get the lookup URI for the profile contact (if it still exists).
Cursor c = resolver.query(Profile.CONTENT_URI, new String[] { Contacts._ID, Contacts.LOOKUP_KEY }, null, null, null);
if (c == null) {
continue;
}
try {
if (c.moveToFirst()) {
final long contactId = c.getLong(0);
final String lookupKey = c.getString(1);
lookupUri = Contacts.getLookupUri(contactId, lookupKey);
}
} finally {
c.close();
}
} else {
final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
lookupUri = RawContacts.getContactLookupUri(resolver, rawContactUri);
}
if (lookupUri != null) {
Log.v(TAG, "Saved contact. New URI: " + lookupUri);
}
// We can change this back to false later, if we fail to save the contact photo.
succeeded = true;
break;
} catch (RemoteException e) {
// Something went wrong, bail without success
Log.e(TAG, "Problem persisting user edits", e);
break;
} catch (IllegalArgumentException e) {
// This is thrown by applyBatch on malformed requests
Log.e(TAG, "Problem persisting user edits", e);
showToast(R.string.contactSavedErrorToast);
break;
} catch (OperationApplicationException e) {
// Version consistency failed, re-parent change and try again
Log.w(TAG, "Version consistency failed, re-parenting: " + e.toString());
final StringBuilder sb = new StringBuilder(RawContacts._ID + " IN(");
boolean first = true;
final int count = state.size();
for (int i = 0; i < count; i++) {
Long rawContactId = state.getRawContactId(i);
if (rawContactId != null && rawContactId != -1) {
if (!first) {
sb.append(',');
}
sb.append(rawContactId);
first = false;
}
}
sb.append(")");
if (first) {
throw new IllegalStateException("Version consistency failed for a new contact", e);
}
final RawContactDeltaList newState = RawContactDeltaList.fromQuery(isProfile ? RawContactsEntity.PROFILE_CONTENT_URI : RawContactsEntity.CONTENT_URI, resolver, sb.toString(), null, null);
state = RawContactDeltaList.mergeAfter(newState, state);
// Update the new state to use profile URIs if appropriate.
if (isProfile) {
for (RawContactDelta delta : state) {
delta.setProfileQueryUri();
}
}
}
}
}
// the ContactProvider already knows about newly-created contacts.
if (updatedPhotos != null) {
for (String key : updatedPhotos.keySet()) {
Uri photoUri = updatedPhotos.getParcelable(key);
long rawContactId = Long.parseLong(key);
// replace the bogus ID with the new one that we actually saved the contact at.
if (rawContactId < 0) {
rawContactId = insertedRawContactId;
}
// If the save failed, insertedRawContactId will be -1
if (rawContactId < 0 || !saveUpdatedPhoto(rawContactId, photoUri, saveMode)) {
succeeded = false;
}
}
}
Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);
if (callbackIntent != null) {
if (succeeded) {
// Mark the intent to indicate that the save was successful (even if the lookup URI
// is now null). For local contacts or the local profile, it's possible that the
// save triggered removal of the contact, so no lookup URI would exist..
callbackIntent.putExtra(EXTRA_SAVE_SUCCEEDED, true);
}
callbackIntent.setData(lookupUri);
deliverCallback(callbackIntent);
}
}
use of com.android.contacts.common.model.RawContactDelta in project packages_apps_Contacts by AOKP.
the class AttachPhotoActivity method saveContact.
/**
* If prerequisites have been met, attach the photo to a raw-contact and save.
* The prerequisites are:
* - photo has been cropped
* - contact has been loaded
*/
private void saveContact(Contact contact) {
if (contact.getRawContacts() == null) {
Log.w(TAG, "No raw contacts found for contact");
finish();
return;
}
// Obtain the raw-contact that we will save to.
RawContactDeltaList deltaList = contact.createRawContactDeltaList();
RawContactDelta raw = deltaList.getFirstWritableRawContact(this);
if (raw == null) {
// We can't directly insert this photo since no raw contacts exist in the contact.
selectAccountAndCreateContact();
return;
}
saveToContact(contact, deltaList, raw);
}
use of com.android.contacts.common.model.RawContactDelta in project packages_apps_Contacts by AOKP.
the class CompactRawContactsEditorView method setState.
public void setState(RawContactDeltaList rawContactDeltas, MaterialColorMapUtils.MaterialPalette materialPalette, ViewIdGenerator viewIdGenerator, long photoId, boolean hasNewContact, boolean isUserProfile, AccountWithDataSet primaryAccount) {
mKindSectionDataMap.clear();
mKindSectionViews.removeAllViews();
mMoreFields.setVisibility(View.VISIBLE);
mMaterialPalette = materialPalette;
mViewIdGenerator = viewIdGenerator;
mPhotoId = photoId;
mHasNewContact = hasNewContact;
mIsUserProfile = isUserProfile;
mPrimaryAccount = primaryAccount;
if (mPrimaryAccount == null) {
mPrimaryAccount = ContactEditorUtils.getInstance(getContext()).getDefaultAccount();
}
vlog("state: primary " + mPrimaryAccount);
// Parse the given raw contact deltas
if (rawContactDeltas == null || rawContactDeltas.isEmpty()) {
elog("No raw contact deltas");
if (mListener != null)
mListener.onBindEditorsFailed();
return;
}
parseRawContactDeltas(rawContactDeltas);
if (mKindSectionDataMap.isEmpty()) {
elog("No kind section data parsed from RawContactDelta(s)");
if (mListener != null)
mListener.onBindEditorsFailed();
return;
}
// Get the primary name kind section data
mPrimaryNameKindSectionData = mKindSectionDataMap.get(StructuredName.CONTENT_ITEM_TYPE).getEntryToWrite(/* id =*/
-1, mPrimaryAccount, mIsUserProfile);
if (mPrimaryNameKindSectionData != null) {
// Ensure that a structured name and photo exists
final RawContactDelta rawContactDelta = mPrimaryNameKindSectionData.first.getRawContactDelta();
RawContactModifier.ensureKindExists(rawContactDelta, rawContactDelta.getAccountType(mAccountTypeManager), StructuredName.CONTENT_ITEM_TYPE);
RawContactModifier.ensureKindExists(rawContactDelta, rawContactDelta.getAccountType(mAccountTypeManager), Photo.CONTENT_ITEM_TYPE);
}
// Setup the view
addAccountInfo(rawContactDeltas);
addPhotoView();
addKindSectionViews();
if (mIsExpanded)
showAllFields();
if (mListener != null)
mListener.onEditorsBound();
}
use of com.android.contacts.common.model.RawContactDelta in project packages_apps_Contacts by AOKP.
the class CompactRawContactsEditorView method parseRawContactDeltas.
private void parseRawContactDeltas(RawContactDeltaList rawContactDeltas) {
// Build the kind section data list map
vlog("parse: " + rawContactDeltas.size() + " rawContactDelta(s)");
for (int j = 0; j < rawContactDeltas.size(); j++) {
final RawContactDelta rawContactDelta = rawContactDeltas.get(j);
vlog("parse: " + j + " rawContactDelta" + rawContactDelta);
if (rawContactDelta == null || !rawContactDelta.isVisible())
continue;
final AccountType accountType = rawContactDelta.getAccountType(mAccountTypeManager);
if (accountType == null)
continue;
final List<DataKind> dataKinds = accountType.getSortedDataKinds();
final int dataKindSize = dataKinds == null ? 0 : dataKinds.size();
vlog("parse: " + dataKindSize + " dataKinds(s)");
for (int i = 0; i < dataKindSize; i++) {
final DataKind dataKind = dataKinds.get(i);
if (dataKind == null || !dataKind.editable) {
vlog("parse: " + i + " " + dataKind.mimeType + " dropped read-only");
continue;
}
final String mimeType = dataKind.mimeType;
// Skip psuedo mime types
if (DataKind.PSEUDO_MIME_TYPE_DISPLAY_NAME.equals(mimeType) || DataKind.PSEUDO_MIME_TYPE_PHONETIC_NAME.equals(mimeType)) {
vlog("parse: " + i + " " + dataKind.mimeType + " dropped pseudo type");
continue;
}
final KindSectionDataList kindSectionDataList = getOrCreateKindSectionDataList(mimeType);
final KindSectionData kindSectionData = new KindSectionData(accountType, dataKind, rawContactDelta);
kindSectionDataList.add(kindSectionData);
vlog("parse: " + i + " " + dataKind.mimeType + " " + kindSectionData.getValuesDeltas().size() + " value(s) " + kindSectionData.getNonEmptyValuesDeltas().size() + " non-empty value(s) " + kindSectionData.getVisibleValuesDeltas().size() + " visible value(s)");
}
}
}
Aggregations