Java Code Examples for android.content.ContentResolver#insert()

The following examples show how to use android.content.ContentResolver#insert() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserDictionary.java    From Chimee with MIT License 6 votes vote down vote up
/**
 * Adds a word to the dictionary, with the default frequency and following words.
 *
 * @param context the current application context
 * @param word    the word to add to the dictionary. This should not be null
 *                or empty.
 */
static void addWord(Context context, String word) {

    final ContentResolver resolver = context.getContentResolver();

    if (TextUtils.isEmpty(word)) {
        return;
    }

    final int COLUMN_COUNT = 3;
    ContentValues values = new ContentValues(COLUMN_COUNT);

    values.put(WORD, word);
    values.put(FREQUENCY, DEFAULT_FREQUENCY);
    values.put(FOLLOWING, "");

    resolver.insert(CONTENT_URI, values);
}
 
Example 2
Source File: ImageHelper.java    From fanfouapp-opensource with Apache License 2.0 6 votes vote down vote up
/**
 * Store a picture that has just been saved to disk in the MediaStore.
 * 
 * @param imageFile
 *            The File of the picture
 * @return The Uri provided by the MediaStore.
 */
public static Uri storePicture(final Context ctx, final File imageFile,
        String imageName) {
    final ContentResolver cr = ctx.getContentResolver();
    imageName = imageName.substring(imageName.lastIndexOf('/') + 1);
    final ContentValues values = new ContentValues(7);
    values.put(MediaColumns.TITLE, imageName);
    values.put(MediaColumns.DISPLAY_NAME, imageName);
    values.put(ImageColumns.DESCRIPTION, "");
    values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
    values.put(MediaColumns.MIME_TYPE, "image/jpeg");
    values.put(ImageColumns.ORIENTATION, 0);
    final File parentFile = imageFile.getParentFile();
    final String path = parentFile.toString().toLowerCase();
    final String name = parentFile.getName().toLowerCase();
    values.put(Images.ImageColumns.BUCKET_ID, path.hashCode());
    values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
    values.put("_data", imageFile.toString());

    final Uri uri = cr.insert(Images.Media.EXTERNAL_CONTENT_URI, values);

    return uri;
}
 
Example 3
Source File: UserDictionary.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/** Adds a word to the dictionary, with the given frequency and the specified
 *  locale type.
 *
 *  @param context the current application context
 *  @param word the word to add to the dictionary. This should not be null or
 *  empty.
 *  @param shortcut optional shortcut spelling for this word. When the shortcut
 *  is typed, the word may be suggested by applications that support it. May be null.
 *  @param locale the locale to insert the word for, or null to insert the word
 *  for all locales.
 */
public static void addWord(Context context, String word,
        int frequency, String shortcut, Locale locale) {
    final ContentResolver resolver = context.getContentResolver();

    if (TextUtils.isEmpty(word)) {
        return;
    }

    if (frequency < FREQUENCY_MIN) frequency = FREQUENCY_MIN;
    if (frequency > FREQUENCY_MAX) frequency = FREQUENCY_MAX;

    final int COLUMN_COUNT = 5;
    ContentValues values = new ContentValues(COLUMN_COUNT);

    values.put(WORD, word);
    values.put(FREQUENCY, frequency);
    values.put(LOCALE, null == locale ? null : locale.toString());
    values.put(APP_ID, 0); // TODO: Get App UID
    values.put(SHORTCUT, shortcut);

    Uri result = resolver.insert(CONTENT_URI, values);
    // It's ok if the insert doesn't succeed because the word
    // already exists.
}
 
Example 4
Source File: RemotePreferenceProviderTest.java    From RemotePreferences with MIT License 6 votes vote down vote up
@Test
public void testInsertPrefFailKeyInUriAndValuesMismatch() {
    ContentValues values = new ContentValues();
    values.put(RemoteContract.COLUMN_KEY, "string");
    values.put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING);
    values.put(RemoteContract.COLUMN_VALUE, "foobar");

    ContentResolver resolver = getLocalContext().getContentResolver();
    try {
        resolver.insert(getQueryUri("string2"), values);
        Assert.fail();
    } catch (IllegalArgumentException e) {
        // Expected
    }

    SharedPreferences prefs = getSharedPreferences();
    Assert.assertEquals("default", prefs.getString("string", "default"));
}
 
Example 5
Source File: ApiCallHandlerThread.java    From PADListener with GNU General Public License v2.0 5 votes vote down vote up
private void savePlayerInfo(CapturedPlayerInfoModel playerInfoModel) {
	MyLog.entry();

	final ContentResolver cr = context.getContentResolver();
	final Uri uri = CapturedPlayerInfoDescriptor.UriHelper.uriForAll();

	Long fake_id = null;

	final Cursor cursor = cr.query(uri, new String[]{CapturedPlayerInfoDescriptor.Fields.FAKE_ID.getColName()}, null, null, null);
	if (cursor != null) {
		if (cursor.moveToNext()) {
			fake_id = cursor.getLong(0);
		}
		cursor.close();
	}

	final ContentValues values = CapturedPlayerInfoProviderHelper.modelToValues(playerInfoModel);

	if (fake_id == null) {
		MyLog.debug("Insert new data");
		cr.insert(uri, values);
	} else {
		MyLog.debug("Update existing data");
		cr.update(uri, values, CapturedPlayerInfoDescriptor.Fields.FAKE_ID.getColName() + " = ?", new String[]{fake_id.toString()});
	}

	MyLog.exit();
}
 
Example 6
Source File: Contacts.java    From intra42 with Apache License 2.0 5 votes vote down vote up
private static String createGroup(Context context) {
    ContentResolver cr = context.getContentResolver();
    ContentValues groupValues = new ContentValues();
    groupValues.put(ContactsContract.Groups.TITLE, "42");
    groupValues.put(ContactsContract.Groups.NOTES, "Ecole 42");
    cr.insert(ContactsContract.Groups.CONTENT_URI, groupValues);
    return getGroupId(context);
}
 
Example 7
Source File: QuantumFlux.java    From QuantumFlux with Apache License 2.0 5 votes vote down vote up
public static <T> T insertAndReturn(T dataModelObject) {
    TableDetails tableDetails = findTableDetails(dataModelObject.getClass());
    ContentValues contentValues = ModelInflater.deflate(tableDetails, dataModelObject);
    Uri insertUri = UriMatcherHelper.generateItemUriBuilder(tableDetails).build();

    ContentResolver contentResolver = mApplicationContext.getContentResolver();
    Uri itemUri = contentResolver.insert(insertUri, contentValues);

    return findSingleItem(itemUri, tableDetails);
}
 
Example 8
Source File: VoicemailContract.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Inserts a list of voicemails into the voicemail content provider.
 *
 * @param context The context of the app doing the inserting
 * @param voicemails Data to be inserted
 * @return the number of voicemails inserted
 *
 * @hide
 */
public static int insert(Context context, List<Voicemail> voicemails) {
    ContentResolver contentResolver = context.getContentResolver();
    int count = voicemails.size();
    for (int i = 0; i < count; i++) {
        ContentValues contentValues = getContentValues(voicemails.get(i));
        contentResolver.insert(buildSourceUri(context.getPackageName()), contentValues);
    }
    return count;
}
 
Example 9
Source File: BinaryDAO.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Inserts a new record for a binary object with no file uri or mime type
 * set.
 *
 * @param cr          A content resolver
 * @param encounterId The encounter identifier
 * @param elementId   The encounter element identifier
 * @return A Uri for locating the new entry or null if unsuccessful.
 */
public static Uri insert(ContentResolver cr, String encounterId,
                         String elementId) {
    Uri result = null;
    ContentValues values = new ContentValues();
    values.put(BinarySQLFormat.ENCOUNTER_ID, encounterId);
    values.put(BinarySQLFormat.ELEMENT_ID, elementId);
    result = cr.insert(BinarySQLFormat.CONTENT_URI, values);

    Log.d(TAG, "Result: " + result);
    return result;
}
 
Example 10
Source File: LauncherBackupHelper.java    From Trebuchet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Read a favorite from the stream.
 *
 * <P>Keys arrive in any order, so screens and containers may not exist yet.
 *
 * @param key identifier for the row
 * @param buffer the serialized proto from the stream, may be larger than dataSize
 * @param dataSize the size of the proto from the stream
 */
private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
    if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
    if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
            Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));

    ContentResolver cr = mContext.getContentResolver();
    ContentValues values = unpackFavorite(buffer, dataSize);
    cr.insert(Favorites.CONTENT_URI, values);
}
 
Example 11
Source File: Imps.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Save a string value of setting in the table providerSetting.
 *
 * @param cr The ContentProvider used to access the providerSetting
 *            table.
 * @param providerId The id of the provider.
 * @param name The name of the setting.
 * @param value The value of the setting.
 */
public static void putStringValue(ContentResolver cr, long providerId, String name,
        String value) {
    ContentValues v = new ContentValues(3);
    v.put(PROVIDER, providerId);
    v.put(NAME, name);
    v.put(VALUE, value);

    cr.insert(CONTENT_URI, v);


}
 
Example 12
Source File: ImConnectionAdapter.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onGroupInvitation(Invitation invitation) {
    String sender = invitation.getSender().getUser();
    ContentValues values = new ContentValues(7);
    values.put(Imps.Invitation.PROVIDER, mProviderId);
    values.put(Imps.Invitation.ACCOUNT, mAccountId);
    values.put(Imps.Invitation.INVITE_ID, invitation.getInviteID());
    values.put(Imps.Invitation.SENDER, sender);
    values.put(Imps.Invitation.GROUP_NAME, invitation.getGroupAddress().getUser());
    values.put(Imps.Invitation.NOTE, invitation.getReason());
    values.put(Imps.Invitation.STATUS, Imps.Invitation.STATUS_PENDING);
    ContentResolver resolver = mService.getContentResolver();
    Uri uri = resolver.insert(Imps.Invitation.CONTENT_URI, values);
    long id = ContentUris.parseId(uri);
    try {
        if (mRemoteListener != null) {
            mRemoteListener.onGroupInvitation(id);
            return;
        }
    } catch (RemoteException e) {
        RemoteImService.debug("onGroupInvitation: dead listener " + mRemoteListener
                              + "; removing", e);
        mRemoteListener = null;
    }
    // No listener registered or failed to notify the listener, send a
    // notification instead.
    mService.getStatusBarNotifier().notifyGroupInvitation(mProviderId, mAccountId, id,
            sender);
}
 
Example 13
Source File: MusicUtil.java    From MusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
public static void insertAlbumArt(@NonNull Context context, int albumId, String path) {
    ContentResolver contentResolver = context.getContentResolver();

    Uri artworkUri = Uri.parse("content://media/external/audio/albumart");
    contentResolver.delete(ContentUris.withAppendedId(artworkUri, albumId), null, null);

    ContentValues values = new ContentValues();
    values.put("album_id", albumId);
    values.put("_data", path);

    contentResolver.insert(artworkUri, values);
}
 
Example 14
Source File: PermissionsChecker.java    From permissions4m with Apache License 2.0 5 votes vote down vote up
/**
 * write and delete contacts info, {@link android.Manifest.permission#WRITE_CONTACTS}
 * and we should get read contacts permission first.
 *
 * @param activity
 * @return true if success
 * @throws Exception
 */
private static boolean checkWriteContacts(Activity activity) throws Exception {
    if (checkReadContacts(activity)) {
        // write some info
        ContentValues values = new ContentValues();
        ContentResolver contentResolver = activity.getContentResolver();
        Uri rawContactUri = contentResolver.insert(ContactsContract.RawContacts
                .CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);
        values.put(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds
                .StructuredName.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, TAG);
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, TAG_NUMBER);
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

        // delete info
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = activity.getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Contacts.Data._ID},
                "display_name=?", new String[]{TAG}, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(0);
                resolver.delete(uri, "display_name=?", new String[]{TAG});
                uri = Uri.parse("content://com.android.contacts/data");
                resolver.delete(uri, "raw_contact_id=?", new String[]{id + ""});
            }
            cursor.close();
        }
        return true;
    } else {
        return false;
    }
}
 
Example 15
Source File: SipProfileJson.java    From CSipSimple with GNU General Public License v3.0 5 votes vote down vote up
private static boolean restoreSipProfile(JSONObject jsonObj, ContentResolver cr) {
    // Restore accounts
    Columns cols;
    ContentValues cv;

    cols = getSipProfileColumns(false);
    cv = cols.jsonToContentValues(jsonObj);

    long profileId = cv.getAsLong(SipProfile.FIELD_ID);
    if(profileId >= 0) {
        Uri insertedUri = cr.insert(SipProfile.ACCOUNT_URI, cv);
        profileId = ContentUris.parseId(insertedUri);
    }
    // TODO : else restore call handler in private db
    
    
    // Restore filters
    cols = new Columns(Filter.FULL_PROJ, Filter.FULL_PROJ_TYPES);
    try {
        JSONArray filtersObj = jsonObj.getJSONArray(FILTER_KEY);
        Log.d(THIS_FILE, "We have filters for " + profileId + " > " + filtersObj.length());
        for (int i = 0; i < filtersObj.length(); i++) {
            JSONObject filterObj = filtersObj.getJSONObject(i);
            // Log.d(THIS_FILE, "restoring "+filterObj.toString(4));
            cv = cols.jsonToContentValues(filterObj);
            cv.put(Filter.FIELD_ACCOUNT, profileId);
            cr.insert(SipManager.FILTER_URI, cv);
        }
    } catch (JSONException e) {
        Log.e(THIS_FILE, "Error while restoring filters", e);
    }

    return false;
}
 
Example 16
Source File: SubjectAdder.java    From android-galaxyzoo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param item
 * @param asyncFileDownloads Get the image data asynchronously if this is true.
 */
private boolean addSubject(final ZooniverseClient.Subject item, final boolean asyncFileDownloads) {
    if (subjectIsInDatabase(item.getId())) {
        //It is already in the database.
        //TODO: Update the row?
        return true;
    }

    final ContentResolver resolver = getContext().getContentResolver();

    final ContentValues values = new ContentValues();
    values.put(Item.Columns.SUBJECT_ID, item.getId());
    values.put(Item.Columns.ZOONIVERSE_ID, item.getZooniverseId());
    values.put(Item.Columns.GROUP_ID, item.getGroupId());

    //The ItemsContentProvider will take care of creating local file URIs for the remote URis,
    //and this SyncAdapter will request that the remote image files are downloaded into those local file URIs.
    values.put(Item.Columns.LOCATION_STANDARD_URI_REMOTE, item.getLocationStandard());
    values.put(Item.Columns.LOCATION_THUMBNAIL_URI_REMOTE, item.getLocationThumbnail());
    values.put(Item.Columns.LOCATION_INVERTED_URI_REMOTE, item.getLocationInverted());

    final Uri itemUri = resolver.insert(Item.ITEMS_URI, values);
    if (itemUri == null) {
        Log.error("could not insert content values: " + values);
        return false;
    }

    cacheUrisToFiles(itemUri, asyncFileDownloads);

    //TODO: notifyRowChangeById(rowId);
    return true;
}
 
Example 17
Source File: MainFragment.java    From continuous-audiorecorder with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Creates new item in the system's media database.
 *
 * @see <a href="https://github.com/android/platform_packages_apps_soundrecorder/blob/master/src/com/android/soundrecorder/SoundRecorder.java">Android Recorder source</a>
 */
public Uri saveCurrentRecordToMediaDB(final String fileName) {
    if (mAudioRecordUri != null) return mAudioRecordUri;

    final Activity activity = getActivity();
    final Resources res = activity.getResources();
    final ContentValues cv = new ContentValues();
    final File file = new File(fileName);
    final long current = System.currentTimeMillis();
    final long modDate = file.lastModified();
    final Date date = new Date(current);
    final String dateTemplate = res.getString(R.string.audio_db_title_format);
    final SimpleDateFormat formatter = new SimpleDateFormat(dateTemplate, Locale.getDefault());
    final String title = formatter.format(date);
    final long sampleLengthMillis = 1;
    // Lets label the recorded audio file as NON-MUSIC so that the file
    // won't be displayed automatically, except for in the playlist.
    cv.put(MediaStore.Audio.Media.IS_MUSIC, "0");

    cv.put(MediaStore.Audio.Media.TITLE, title);
    cv.put(MediaStore.Audio.Media.DATA, file.getAbsolutePath());
    cv.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
    cv.put(MediaStore.Audio.Media.DATE_MODIFIED, (int) (modDate / 1000));
    cv.put(MediaStore.Audio.Media.DURATION, sampleLengthMillis);
    cv.put(MediaStore.Audio.Media.MIME_TYPE, "audio/*");
    cv.put(MediaStore.Audio.Media.ARTIST, res.getString(R.string.audio_db_artist_name));
    cv.put(MediaStore.Audio.Media.ALBUM, res.getString(R.string.audio_db_album_name));

    Log.d(TAG, "Inserting audio record: " + cv.toString());

    final ContentResolver resolver = activity.getContentResolver();
    final Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Log.d(TAG, "ContentURI: " + base);

    mAudioRecordUri = resolver.insert(base, cv);
    if (mAudioRecordUri == null) {
        return null;
    }
    activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, mAudioRecordUri));
    return mAudioRecordUri;
}
 
Example 18
Source File: CallLog.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private static Uri addEntryAndRemoveExpiredEntries(Context context, UserManager userManager,
        UserHandle user, ContentValues values) {
    final ContentResolver resolver = context.getContentResolver();

    // Since we're doing this operation on behalf of an app, we only
    // want to use the actual "unlocked" state.
    final Uri uri = ContentProvider.maybeAddUserId(
            userManager.isUserUnlocked(user) ? CONTENT_URI : SHADOW_CONTENT_URI,
            user.getIdentifier());

    if (VERBOSE_LOG) {
        Log.v(LOG_TAG, String.format("Inserting to %s", uri));
    }

    try {
        // When cleaning up the call log, try to delete older call long entries on a per
        // PhoneAccount basis first.  There can be multiple ConnectionServices causing
        // the addition of entries in the call log.  With the introduction of Self-Managed
        // ConnectionServices, we want to ensure that a misbehaving self-managed CS cannot
        // spam the call log with its own entries, causing entries from Telephony to be
        // removed.
        final Uri result = resolver.insert(uri, values);
        if (values.containsKey(PHONE_ACCOUNT_ID)
                && !TextUtils.isEmpty(values.getAsString(PHONE_ACCOUNT_ID))
                && values.containsKey(PHONE_ACCOUNT_COMPONENT_NAME)
                && !TextUtils.isEmpty(values.getAsString(PHONE_ACCOUNT_COMPONENT_NAME))) {
            // Only purge entries for the same phone account.
            resolver.delete(uri, "_id IN " +
                    "(SELECT _id FROM calls"
                    + " WHERE " + PHONE_ACCOUNT_COMPONENT_NAME + " = ?"
                    + " AND " + PHONE_ACCOUNT_ID + " = ?"
                    + " ORDER BY " + DEFAULT_SORT_ORDER
                    + " LIMIT -1 OFFSET 500)", new String[] {
                    values.getAsString(PHONE_ACCOUNT_COMPONENT_NAME),
                    values.getAsString(PHONE_ACCOUNT_ID)
            });
        } else {
            // No valid phone account specified, so default to the old behavior.
            resolver.delete(uri, "_id IN " +
                    "(SELECT _id FROM calls ORDER BY " + DEFAULT_SORT_ORDER
                    + " LIMIT -1 OFFSET 500)", null);
        }

        return result;
    } catch (IllegalArgumentException e) {
        Log.w(LOG_TAG, "Failed to insert calllog", e);
        // Even though we make sure the target user is running and decrypted before calling
        // this method, there's a chance that the user just got shut down, in which case
        // we'll still get "IllegalArgumentException: Unknown URL content://call_log/calls".
        return null;
    }
}
 
Example 19
Source File: MediaSharing.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
@Override
public Uri shareVideo(final @NonNull Context context,
                      final @NonNull File videoFile,
                      final @NonNull FileManager fileManager) {
    if (checkMediaFile(videoFile)) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(MediaStore.Video.Media.TITLE, videoFile.getName());
        values.put(MediaStore.Video.Media.DISPLAY_NAME, videoFile.getName());
        values.put(MediaStore.Video.Media.ARTIST, "DeviceConnect");
        values.put(MediaStore.Video.Media.MIME_TYPE, "video/avc");
        values.put(MediaStore.Video.Media.DATA, videoFile.toString());
        Uri uri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);

        // 動画IDをサムネイルDBに挿入.
        try {
            if (uri != null) {
                String id = uri.getLastPathSegment();
                if (id != null) {
                    long videoId = Long.parseLong(id);
                    long thumbnailId = registerVideoThumbnail(context, videoFile, videoId, fileManager);
                    boolean updated = updateThumbnailInfo(context, thumbnailId, videoId);
                    if (updated) {
                        if (DEBUG) {
                            Log.d(TAG, "Updated videoID on thumbnail info: videoId="
                                    + videoId + ", thumbnailId=" + thumbnailId);
                        }
                    } else {
                        Log.w(TAG, "Failed to update videoID on thumbnail info: videoId="
                                + videoId + ", thumbnailId=" + thumbnailId);
                    }

                }
                return uri;
            }
        } catch (NumberFormatException e) {
            Log.w(TAG, "Failed to parse videoID as long type: video URI=" + uri, e);
        }
    }
    return null;
}
 
Example 20
Source File: Contacts.java    From android_9.0.0_r45 with Apache License 2.0 3 votes vote down vote up
/**
 * Adds a person to a group.
 *
 * @param resolver the resolver to use
 * @param personId the person to add to the group
 * @param groupId the group to add the person to
 * @return the URI of the group membership row
 * @deprecated see {@link android.provider.ContactsContract}
 */
@Deprecated
public static Uri addToGroup(ContentResolver resolver, long personId, long groupId) {
    ContentValues values = new ContentValues();
    values.put(GroupMembership.PERSON_ID, personId);
    values.put(GroupMembership.GROUP_ID, groupId);
    return resolver.insert(GroupMembership.CONTENT_URI, values);
}