下面列出了怎么用android.content.ContentUris的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
logger.debug("insert({})", uri);
if (uriMatcher.match(uri) != MAP_OBJECTS) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (values == null) {
throw new IllegalArgumentException("Values can not be null");
}
MapObject mo = new MapObject(0, 0);
populateFields(mo, values);
long id = MapTrek.addMapObject(mo);
Uri objectUri = ContentUris.withAppendedId(DataContract.MAPOBJECTS_URI, id);
Context context = getContext();
if (context != null)
context.getContentResolver().notifyChange(objectUri, null);
return objectUri;
}
@Override
public ContactInfo getContactInfo(Context context, Cursor cursor) {
ContactInfo ci = new ContactInfo();
// Get values
ci.displayName = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
ci.contactId = cursor.getLong(cursor.getColumnIndex(Contacts._ID));
ci.callerInfo.contactContentUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, ci.contactId);
ci.callerInfo.photoId = cursor.getLong(cursor.getColumnIndex(Contacts.PHOTO_ID));
int photoUriColIndex = cursor.getColumnIndex(Contacts.PHOTO_ID);
ci.status = cursor.getString(cursor.getColumnIndex(Contacts.CONTACT_STATUS));
ci.presence = cursor.getInt(cursor.getColumnIndex(Contacts.CONTACT_PRESENCE));
if (photoUriColIndex >= 0) {
String photoUri = cursor.getString(photoUriColIndex);
if (!TextUtils.isEmpty(photoUri)) {
ci.callerInfo.photoUri = Uri.parse(photoUri);
}
}
ci.hasPresence = !TextUtils.isEmpty(ci.status);
return ci;
}
@Override
public boolean test() throws Throwable {
try {
Uri mBaseUri = VoicemailContract.Voicemails.CONTENT_URI;
ContentValues contentValues = new ContentValues();
contentValues.put(VoicemailContract.Voicemails.DATE, System.currentTimeMillis());
contentValues.put(VoicemailContract.Voicemails.NUMBER, "1");
contentValues.put(VoicemailContract.Voicemails.DURATION, 1);
contentValues.put(VoicemailContract.Voicemails.SOURCE_PACKAGE, "permission");
contentValues.put(VoicemailContract.Voicemails.SOURCE_DATA, "permission");
contentValues.put(VoicemailContract.Voicemails.IS_READ, 0);
Uri newVoicemailUri = mResolver.insert(mBaseUri, contentValues);
long id = ContentUris.parseId(newVoicemailUri);
int count = mResolver.delete(mBaseUri, VoicemailContract.Voicemails._ID + "=?",
new String[] {Long.toString(id)});
return count > 0;
} catch (Exception e) {
String message = e.getMessage();
if (!TextUtils.isEmpty(message)) {
message = message.toLowerCase();
return !message.contains("add_voicemail");
}
return false;
}
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private static String getKitKatPathFromMediaUri(Context context, Uri uri) {
String imagePath = "";
if (DocumentsContract.isDocumentUri(context, uri)) {
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
//Log.d(TAG, uri.toString());
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePathFromMediaUri(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
//Log.d(TAG, uri.toString());
Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(docId));
imagePath = getImagePathFromMediaUri(context, contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
//Log.d(TAG, "content: " + uri.toString());
imagePath = getImagePathFromMediaUri(context, uri, null);
}
return imagePath;
}
public static void saveInTransaction(Context context, List<? extends CPDefaultRecord> records) throws RemoteException, OperationApplicationException {
List<ContentProviderOperation> operations = prepareTransaction(context, records);
ContentProviderResult[] contentProviderResults = CPOrm.applyPreparedOperations(operations);
Map<Class, Long> referenceIds = new HashMap<>();
for (int i = 0; i < contentProviderResults.length; i++) {
ContentProviderResult result = contentProviderResults[i];
CPDefaultRecord source = records.get(i);
referenceIds.remove(source.getClass());
if(result.uri != null && source.getId() == null && ContentUris.parseId(result.uri) != -1){
source.setId(ContentUris.parseId(result.uri));
referenceIds.put(source.getClass(), source.getId());
}
try {
applyReferenceResults(source.getClass(), source, referenceIds);
} catch (IllegalAccessException e) {
CPOrmLog.e("Failed to apply back reference id's for uri " + result.uri);
}
}
}
public boolean delete(@NonNull Uri uri) {
switch (MATCHER.match(uri)) {
case MATCH_OLD:
case MATCH_NEW:
long id = ContentUris.parseId(uri);
cache.remove(id);
return getFile(ContentUris.parseId(uri)).delete();
default:
break;
}
if (isExternalBlobUri(context, uri)) {
String fileAuthority = BuildConfig.BCM_APPLICATION_ID + ".fileprovider";
if (fileAuthority.equals(uri.getAuthority())) {
return context.getContentResolver().delete(uri, null, null) > 0;
}else {
return new File(uri.getPath()).delete();
}
}
return false;
}
public static Filter getFilterFromDbId(Context ctxt, long filterId, String[] projection) {
Filter filter = new Filter();
if(filterId >= 0) {
Cursor c = ctxt.getContentResolver().query(ContentUris.withAppendedId(SipManager.FILTER_ID_URI_BASE, filterId),
projection, null, null, null);
if(c != null) {
try {
if(c.getCount() > 0) {
c.moveToFirst();
filter = new Filter(c);
}
}catch(Exception e) {
Log.e(THIS_FILE, "Something went wrong while retrieving the account", e);
} finally {
c.close();
}
}
}
return filter;
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
if (mValues != null) {
// Move the Cursor to the correct position, extract the
// search result values, and assign them to the UI for
// each search result.
mValues.moveToPosition(position);
holder.mNameView.setText(mValues.getString(mHoardNameIndex));
holder.mAmountView.setText(mValues.getString(mHoardAmountIndex));
// Create a Uri that points to this search result item.
int rowId = mValues.getInt(mHoardIdIndex);
final Uri rowAddress =
ContentUris.withAppendedId(MyHoardContentProvider.CONTENT_URI, rowId);
// Return the Uri to this search result item if clicked.
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mClickListener.onListItemClick(rowAddress);
}
});
}
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
Uri returnUri = null;
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
String tableName = DatabaseManager.matchUri(uri);
long rowId = -1;
try {
db.beginTransaction();
rowId = db.replace(tableName, null, values);
return rowId > 0
? ContentUris.withAppendedId(uri, rowId)
: ContentUris.withAppendedId(uri, -1);
} catch (SQLException e) {
Log.e(TAG, "insert " + tableName + " error: " + e);
e.printStackTrace();
} finally {
db.endTransaction();
}
return returnUri;
}
private String getGroupCount(ContentResolver resolver, long groupId) {
String[] projection = { Imps.GroupMembers.NICKNAME };
Uri uri = ContentUris.withAppendedId(Imps.GroupMembers.CONTENT_URI, groupId);
Cursor c = resolver.query(uri, projection, null, null, null);
StringBuilder buf = new StringBuilder();
if (c != null) {
buf.append(" (");
buf.append(c.getCount());
buf.append(")");
c.close();
}
return buf.toString();
}
/**
* Creates a new contacts and adds it to the "My Contacts" group.
*
* @param resolver the ContentResolver to use
* @param values the values to use when creating the contact
* @return the URI of the contact, or null if the operation fails
* @deprecated see {@link android.provider.ContactsContract}
*/
@Deprecated
public static Uri createPersonInMyContactsGroup(ContentResolver resolver,
ContentValues values) {
Uri contactUri = resolver.insert(People.CONTENT_URI, values);
if (contactUri == null) {
Log.e(TAG, "Failed to create the contact");
return null;
}
if (addToMyContactsGroup(resolver, ContentUris.parseId(contactUri)) == null) {
resolver.delete(contactUri, null, null);
return null;
}
return contactUri;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
String table;
Uri newUri;
switch (URI_MATCHER.match(uri)) {
case CONNECTION_ALL:
table = TABLE_NAME_CONNECTIONS;
newUri = CONNECTION_URI;
break;
case QUERY_ALL:
table = TABLE_NAME_QUERIES;
newUri = QUERY_URI;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
long id = mDatabase.insert(table, null, values);
newUri = ContentUris.withAppendedId(newUri, id);
getContext().getContentResolver().notifyChange(newUri, null);
Log.d(LOG_TAG, "Insert " + id);
return newUri;
}
/**
* 4.4以后
*
* @param data
*/
@SuppressLint("NewApi")
private void handleImageOnKitKat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
if (DocumentsContract.isDocumentUri(this, uri)) {
// 如果是document类型的Uri,则通过document id处理
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1]; // 解析出数字格式的id
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
// 如果是content类型的Uri,则使用普通方式处理
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
// 如果是file类型的Uri,直接获取图片路径即可
imagePath = uri.getPath();
}
displayImage(imagePath); // 根据图片路径显示图片
}
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
processIntent(intent);
mConvoView.setSelected(true);
IntentFilter regFilter = new IntentFilter();
regFilter .addAction(Intent.ACTION_SCREEN_OFF);
regFilter .addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(receiver, regFilter);
// Set last read date now!
if (mChatId != -1) {
ContentValues values = new ContentValues(1);
values.put(Imps.Chats.LAST_READ_DATE, System.currentTimeMillis());
getContentResolver().update(ContentUris.withAppendedId(Imps.Chats.CONTENT_URI, mChatId), values, null, null);
}
}
/**
* Helper method to retrieve a SipProfile object from its account database
* id.<br/>
* You have to specify the projection you want to use for to retrieve infos.<br/>
* As consequence the wrapper SipProfile object you'll get may be
* incomplete. So take care if you try to reinject it by updating to not
* override existing values of the database that you don't get here.
*
* @param ctxt Your application context. Mainly useful to get the content provider for the request.
* @param accountId The sip profile {@link #FIELD_ID} you want to retrieve.
* @param projection The list of fields you want to retrieve. Must be in FIELD_* of this class.<br/>
* Reducing your requested fields to minimum will improve speed of the request.
* @return A wrapper SipProfile object on the request you done. If not found an invalid account with an {@link #id} equals to {@link #INVALID_ID}
*/
public static SipProfile getProfileFromDbId(Context ctxt, long accountId, String[] projection) {
SipProfile account = new SipProfile();
if (accountId != INVALID_ID) {
Cursor c = ctxt.getContentResolver().query(
ContentUris.withAppendedId(ACCOUNT_ID_URI_BASE, accountId),
projection, null, null, null);
if (c != null) {
try {
if (c.getCount() > 0) {
c.moveToFirst();
account = new SipProfile(c);
}
} catch (Exception e) {
Log.e(THIS_FILE, "Something went wrong while retrieving the account", e);
} finally {
c.close();
}
}
}
return account;
}
@Override
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
int itemId = item.getItemId();
if(itemId == R.id.set_group) {
showDialogForGroupSelection(context, profileId, groupName);
return true;
}else if(itemId == R.id.share_presence) {
ContentValues cv = new ContentValues();
cv.put(SipProfile.FIELD_PUBLISH_ENABLED, publishEnabled ? 0 : 1);
context.getContentResolver().update(ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, profileId), cv, null, null);
return true;
}else if(itemId == R.id.set_sip_data) {
showDialogForSipData(context, profileId, groupName, domain);
return true;
}
return false;
}
/**
* Method called to handle query requests from client
* applications. This plays the role of the "concrete hook
* method" in the Template Method pattern.
*/
@Override
public Cursor queryCharacter(Uri uri,
String[] projection,
String selection,
String[] selectionArgs,
String sortOrder) {
final MatrixCursor cursor =
new MatrixCursor(CharacterContract.CharacterEntry.sColumnsToDisplay);
// Just return a single item from the database.
long requestId = ContentUris.parseId(uri);
synchronized (this) {
CharacterRecord cr =
mCharacterMap.get(requestId);
if (cr != null) {
buildCursorConditionally(cursor,
cr,
selection,
selectionArgs);
}
}
return cursor;
}
private static void removeEventFromCalendar(Context context, int event) {
Uri eventsUri = Uri.parse("content://com.android.calendar/events");
ContentResolver resolver = context.getContentResolver();
String selection = CalendarContract.Events.CUSTOM_APP_URI + " = ?";
String[] selectionArgs = {getEventUri(event)};
Cursor cursor = resolver.query(eventsUri, new String[]{"_id"}, selection, selectionArgs, null);
while (cursor.moveToNext()) {
long eventId = cursor.getLong(cursor.getColumnIndex("_id"));
resolver.delete(ContentUris.withAppendedId(eventsUri, eventId), null, null);
}
cursor.close();
}
public void testDeleteMovieById() {
ContentValues testValues = TestUtilities.createTestMovieValues();
Uri movieUri = mContext.getContentResolver().insert(MoviesContract.MovieEntry.CONTENT_URI, testValues);
assertTrue(movieUri != null);
long id = ContentUris.parseId(movieUri);
assertTrue(id != -1);
assertEquals(MoviesContract.MovieEntry.buildMovieUri(id), movieUri);
TestUtilities.TestContentObserver moviesObserver = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(MoviesContract.MovieEntry.CONTENT_URI, true, moviesObserver);
TestUtilities.TestContentObserver movieByIdObserver = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(movieUri, true, movieByIdObserver);
mContext.getContentResolver().delete(
MoviesContract.MovieEntry.buildMovieUri(id),
null,
null
);
moviesObserver.waitForNotificationOrFail();
movieByIdObserver.waitForNotificationOrFail();
mContext.getContentResolver().unregisterContentObserver(moviesObserver);
mContext.getContentResolver().unregisterContentObserver(movieByIdObserver);
}
static void deleteBookmarksForTrack(Context context, long trackId) {
// Get all bookmarks associated with the trackId
String[] columns = new String[]{AnchorContract.BookmarkEntry._ID, AnchorContract.BookmarkEntry.COLUMN_AUDIO_FILE};
String sel = AnchorContract.BookmarkEntry.COLUMN_AUDIO_FILE + "=?";
String[] selArgs = {Long.toString(trackId)};
Cursor c = context.getContentResolver().query(AnchorContract.BookmarkEntry.CONTENT_URI,
columns, sel, selArgs, null, null);
// Bail early if the cursor is null
if (c == null) {
return;
} else if (c.getCount() < 1) {
c.close();
return;
}
while (c.moveToNext()) {
// Delete bookmarks associated with the track from the database
int bookmarkId = c.getInt(c.getColumnIndex(AnchorContract.BookmarkEntry._ID));
Uri deleteUri = ContentUris.withAppendedId(AnchorContract.BookmarkEntry.CONTENT_URI, bookmarkId);
context.getContentResolver().delete(deleteUri, null, null);
}
c.close();
}
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
final long filterId = filterIdFromContextMenuInfo(item.getMenuInfo());
if (filterId == -1) {
// For some reason the requested item isn't available, do nothing
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case MENU_ITEM_DELETE: {
getActivity().getContentResolver().delete(ContentUris.withAppendedId(SipManager.FILTER_ID_URI_BASE, filterId), null, null);
return true;
}
case MENU_ITEM_MODIFY : {
showDetails(filterId);
return true;
}
}
return super.onContextItemSelected(item);
}
/**
* @param data
* @return 图片路径
*/
public static String handleImageOnKitKat(Intent data) {
String imagePath = "";
Log.i(TAG, "handleImageOnKitKat: ");
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(MyApplication.getContext(), uri)) {
//如果是document类型的uri,则通过document id处理
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];//解析出数字格式的ID
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
//如果是content类型的uri,则使用普通的方式处理
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
//如果是file类型的uri,直接获取图片路径即可
imagePath = uri.getPath();
}
return imagePath;
}
private String buildSelection(Uri uri, String selection) {
long id;
String additionalSelection = null;
switch (MATCHER.match(uri)) {
case TYPE_LOG_BUFFER:
id = ContentUris.parseId(uri);
additionalSelection = BufferScheme._ID + " = " + id;
break;
case TYPE_LOG_BUFFERS:
// do nothing
break;
default:
throw new IllegalArgumentException("unknown uri: " + uri);
}
if (additionalSelection == null) {
return selection;
}
if (selection == null) {
return additionalSelection;
}
return additionalSelection + " AND " + selection;
}
public EssFile(long id, String mimeType) {
this.mimeType = mimeType;
Uri contentUri;
if (isImage()) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if (isVideo()) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else {
// ?
contentUri = MediaStore.Files.getContentUri("external");
}
this.uri = ContentUris.withAppendedId(contentUri, id);
}
public void testDeleteMostPopularMovies() {
ContentValues testValues = TestUtilities.createTestMovieValues();
Uri movieUri = mContext.getContentResolver().insert(MoviesContract.MovieEntry.CONTENT_URI, testValues);
assertTrue(movieUri != null);
long movieRowId = ContentUris.parseId(movieUri);
assertTrue(movieRowId != -1);
ContentValues entryValues = new ContentValues();
entryValues.put(MoviesContract.COLUMN_MOVIE_ID_KEY, movieRowId);
Uri entryUri = mContext.getContentResolver().insert(MoviesContract.MostPopularMovies.CONTENT_URI, entryValues);
assertTrue(entryUri != null);
TestUtilities.TestContentObserver observer = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(MoviesContract.MostPopularMovies.CONTENT_URI, true, observer);
mContext.getContentResolver().delete(
MoviesContract.MostPopularMovies.CONTENT_URI,
null,
null
);
// Did our content observer get called?
observer.waitForNotificationOrFail();
mContext.getContentResolver().unregisterContentObserver(observer);
Cursor movies = mContext.getContentResolver().query(
MoviesContract.MostPopularMovies.CONTENT_URI,
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
assertNotNull(movies);
assertTrue(movies.getCount() == 0);
movies.close();
}
public static void setRingtone(AppCompatActivity context, long id) {
if (!checkSystemWritePermission(context)) return;
ContentResolver resolver = context.getContentResolver();
Uri ringUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
try {
ContentValues values = new ContentValues(2);
values.put(MediaStore.Audio.Media.IS_RINGTONE, "1");
values.put(MediaStore.Audio.Media.IS_ALARM, "1");
resolver.update(ringUri, values, null, null);
} catch (UnsupportedOperationException ex) {
Log.e("Notset", "couldn't set ringtone flag for id " + id);
return;
}
String[] cols = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.TITLE
};
String where = MediaStore.Audio.Media._ID + "=" + id;
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
cols, where, null, null);
try {
if (cursor != null && cursor.getCount() == 1) {
cursor.moveToFirst();
Settings.System.putString(resolver, Settings.System.RINGTONE, ringUri.toString());
String message = context.getString(R.string.ringtone_set);
String filename = '"' + cursor.getString(2) + '"';
Toast.makeText(context, filename + " " + message, Toast.LENGTH_SHORT).show();
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@Test
public void testContactPickerStubWithExtraMatcher() {
Uri dummyContactDataUri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, CONTACT_ID);
EspContactStub.register(dummyContactDataUri, Activity.RESULT_OK, IntentMatchers.hasExtraWithKey("MyKey"));
Intent contactPickerIntent = createContactPickerIntent();
contactPickerIntent.putExtra("MyKey", "myValue");
activity.startForResult(contactPickerIntent, REQUEST_CODE);
requestCodeTextView.assertTextIs(String.valueOf(REQUEST_CODE));
resultCodeTextView.assertTextIs(String.valueOf(Activity.RESULT_OK));
dataTextView.assertTextIs(dummyContactDataUri.toString());
}
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
// Get access to the task database (to write new data to)
final SQLiteDatabase db = mTaskDbHelper.getWritableDatabase();
// Write URI matching code to identify the match for the tasks directory
int match = sUriMatcher.match(uri);
Uri returnUri; // URI to be returned
switch (match) {
case TASKS:
// Insert new values into the database
// Inserting values into tasks table
long id = db.insert(TABLE_NAME, null, values);
if ( id > 0 ) {
returnUri = ContentUris.withAppendedId(TaskContract.TaskEntry.CONTENT_URI, id);
} else {
throw new android.database.SQLException("Failed to insert row into " + uri);
}
break;
// Set the value for the returnedUri and write the default case for unknown URI's
// Default case throws an UnsupportedOperationException
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
// Notify the resolver if the uri has been changed, and return the newly inserted URI
getContext().getContentResolver().notifyChange(uri, null);
// Return constructed uri (this points to the newly inserted row of data)
return returnUri;
}
/**
* Open contact edit page in default contacts app by contact's id
*
* @param activity
* @param contactId
*/
public static void openContactToEditById(Activity activity, long contactId) {
try {
Intent intent = new Intent(Intent.ACTION_EDIT, ContactsContract.Contacts.CONTENT_URI);
intent.setData(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId));
intent.putExtra("finishActivityOnSaveCompleted", true);
//add the below line?
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivityForResult(intent, 1);
} catch (Exception e) {
Toast.makeText(activity, "Oops there was a problem trying to open the contact :(", Toast.LENGTH_SHORT).show();
}
}
public static Intent prepareEditContactIntentWithSipAddress(int id, String sipUri) {
Intent intent = new Intent(Intent.ACTION_EDIT, Contacts.CONTENT_URI);
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, id);
intent.setData(contactUri);
ArrayList<ContentValues> data = new ArrayList<ContentValues>();
ContentValues sipAddressRow = new ContentValues();
sipAddressRow.put(Contacts.Data.MIMETYPE, SipAddress.CONTENT_ITEM_TYPE);
sipAddressRow.put(SipAddress.SIP_ADDRESS, sipUri);
data.add(sipAddressRow);
intent.putParcelableArrayListExtra(Insert.DATA, data);
return intent;
}