Example usage for android.content ContentResolver insert

List of usage examples for android.content ContentResolver insert

Introduction

In this page you can find the example usage for android.content ContentResolver insert.

Prototype

public final @Nullable Uri insert(@RequiresPermission.Write @NonNull Uri url, @Nullable ContentValues values) 

Source Link

Document

Inserts a row into a table at the given URL.

Usage

From source file:org.awesomeapp.messenger.ui.legacy.DatabaseUtils.java

public static void insertAvatarBlob(ContentResolver resolver, Uri updateUri, long providerId, long accountId,
        byte[] data, String hash, String contact) {

    ContentValues values = new ContentValues(5);
    values.put(Imps.Avatars.CONTACT, contact);
    values.put(Imps.Avatars.DATA, data);
    values.put(Imps.Avatars.PROVIDER, providerId);
    values.put(Imps.Avatars.ACCOUNT, accountId);
    values.put(Imps.Avatars.HASH, hash);
    resolver.insert(updateUri, values);

}

From source file:Main.java

public static void IcsMakeNewCalendarEntry(String title, String description, String location, long startTime,
        long endTime, int allDay, int hasAlarm, int calendarId, int selectedReminderValue) {

    ContentResolver cr = activityObj.getContentResolver();
    ContentValues values = new ContentValues();
    values.put(Events.DTSTART, startTime);
    values.put(Events.DTEND, endTime);/*from w w  w.  j a  va 2 s. co  m*/
    values.put(Events.TITLE, title);
    values.put(Events.DESCRIPTION, description);
    values.put(Events.CALENDAR_ID, calendarId);

    if (allDay == 1) {
        values.put(Events.ALL_DAY, true);
    }

    if (hasAlarm == 1) {
        values.put(Events.HAS_ALARM, true);
    }

    //Get current timezone
    values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
    Log.i(DEBUG_TAG, "Timezone retrieved=>" + TimeZone.getDefault().getID());
    Uri uri = cr.insert(Events.CONTENT_URI, values);
    Log.i(DEBUG_TAG, "Uri returned=>" + uri.toString());
    // get the event ID that is the last element in the Uri
    long eventID = Long.parseLong(uri.getLastPathSegment());

    if (hasAlarm == 1) {
        ContentValues reminders = new ContentValues();
        reminders.put(Reminders.EVENT_ID, eventID);
        reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
        reminders.put(Reminders.MINUTES, selectedReminderValue);

        Uri uri2 = cr.insert(Reminders.CONTENT_URI, reminders);
    }

}

From source file:Main.java

/**
 * A copy of the Android internals StoreThumbnail method, it used with the insertImage to
 * populate the android.provider.MediaStore.Images.Media#insertImage with all the correct
 * meta data. The StoreThumbnail method is private so it must be duplicated here.
 * @see android.provider.MediaStore.Images.Media (StoreThumbnail private method)
 *//* www.ja v a 2 s .  c o m*/
private static final Bitmap storeThumbnail(ContentResolver cr, Bitmap source, long id, float width,
        float height, int kind) {

    // create the matrix to scale it
    Matrix matrix = new Matrix();

    float scaleX = width / source.getWidth();
    float scaleY = height / source.getHeight();

    matrix.setScale(scaleX, scaleY);

    Bitmap thumb = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);

    ContentValues values = new ContentValues(4);
    values.put(MediaStore.Images.Thumbnails.KIND, kind);
    values.put(MediaStore.Images.Thumbnails.IMAGE_ID, (int) id);
    values.put(MediaStore.Images.Thumbnails.HEIGHT, thumb.getHeight());
    values.put(MediaStore.Images.Thumbnails.WIDTH, thumb.getWidth());

    Uri url = cr.insert(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, values);

    try {
        OutputStream thumbOut = cr.openOutputStream(url);
        thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut);
        thumbOut.close();
        return thumb;
    } catch (FileNotFoundException ex) {
        return null;
    } catch (IOException ex) {
        return null;
    }
}

From source file:Main.java

/**
 * Store a picture that has just been saved to disk in the MediaStore.
 * // w  w  w  . j  a v  a  2s.  com
 * @param imageFile
 *            The File of the picture
 * @return The Uri provided by the MediaStore.
 */
public static Uri storePicture(Context ctx, File imageFile, String imageName) {
    ContentResolver cr = ctx.getContentResolver();
    imageName = imageName.substring(imageName.lastIndexOf('/') + 1);
    ContentValues values = new ContentValues(7);
    values.put(Images.Media.TITLE, imageName);
    values.put(Images.Media.DISPLAY_NAME, imageName);
    values.put(Images.Media.DESCRIPTION, "");
    values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
    values.put(Images.Media.MIME_TYPE, "image/jpeg");
    values.put(Images.Media.ORIENTATION, 0);
    File parentFile = imageFile.getParentFile();
    String path = parentFile.toString().toLowerCase();
    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());

    Uri uri = cr.insert(sStorageURI, values);

    return uri;
}

From source file:com.marvin.rocklock.PlaylistUtils.java

/**
 * Adds a given song to an existing playlist
 *
 * @param context the managing activity/*from w w  w.ja  v  a2  s . c om*/
 * @param playlistId the playlist id to append
 * @param id the song id to add
 */
private static void addToPlaylist(RockLockActivity context, int playlistId, String id) {
    ContentResolver resolver = context.getContentResolver();
    Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    // Get most recent play order ID from playlist, so we can append
    Cursor orderCursor = resolver.query(uri, new String[] { MediaStore.Audio.Playlists.Members.PLAY_ORDER },
            null, null, MediaStore.Audio.Playlists.Members.PLAY_ORDER + " DESC ");

    int playOrder = 0;
    if (orderCursor != null) {
        if (orderCursor.moveToFirst()) {
            playOrder = orderCursor.getInt(0) + 1;
        }
        orderCursor.close();
    }

    ContentValues value = new ContentValues();
    value.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, id);
    value.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, playOrder++);
    resolver.insert(uri, value);
}

From source file:android.provider.Checkin.java

/**
 * Helper function to report a crash./*from  w ww.  j av a 2s  . c  o m*/
 *
 * @param resolver from {@link android.content.Context#getContentResolver}
 * @param crash data from {@link android.server.data.CrashData}
 * @return URI of the crash report that was added
 */
static public Uri reportCrash(ContentResolver resolver, byte[] crash) {
    try {
        // If we are in a situation where crash reports fail (such as a full disk),
        // it's important that we don't get into a loop trying to report failures.
        // So discard all crash reports for a few seconds after reporting fails.
        long realtime = SystemClock.elapsedRealtime();
        if (realtime - sLastCrashFailureRealtime < MIN_CRASH_FAILURE_RETRY) {
            Log.e(TAG, "Crash logging skipped, too soon after logging failure");
            return null;
        }

        // HACK: we don't support BLOB values, so base64 encode it.
        byte[] encoded = Base64.encodeBase64(crash);
        ContentValues values = new ContentValues();
        values.put(Crashes.DATA, new String(encoded));
        Uri uri = resolver.insert(Crashes.CONTENT_URI, values);
        if (uri == null) {
            Log.e(TAG, "Error reporting crash");
            sLastCrashFailureRealtime = SystemClock.elapsedRealtime();
        }
        return uri;
    } catch (Throwable t) {
        // To avoid an infinite crash-reporting loop, swallow all errors and exceptions.
        Log.e(TAG, "Error reporting crash: " + t);
        sLastCrashFailureRealtime = SystemClock.elapsedRealtime();
        return null;
    }
}

From source file:com.filemanager.free.filesystem.FileUtil.java

public static boolean rmdir(final File file, Context context) {
    if (file == null)
        return false;
    if (!file.exists()) {
        return true;
    }// w  w  w  . j a va2  s . c o m
    if (!file.isDirectory()) {
        return false;
    }
    String[] fileList = file.list();
    if (fileList != null && fileList.length > 0) {
        //  empty the folder.
        rmdir1(file, context);
    }
    String[] fileList1 = file.list();
    if (fileList1 != null && fileList1.length > 0) {
        // Delete only empty folder.
        return false;
    }
    // Try the normal way
    if (file.delete()) {
        return true;
    }

    // Try with Storage Access Framework.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DocumentFile document = getDocumentFile(file, true, context);
        return document.delete();
    }

    // Try the Kitkat workaround.
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
        resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        // Delete the created entry, such that content provider will delete the file.
        resolver.delete(MediaStore.Files.getContentUri("external"), MediaStore.MediaColumns.DATA + "=?",
                new String[] { file.getAbsolutePath() });
    }

    return !file.exists();
}

From source file:net.niyonkuru.koodroid.appwidget.WidgetConfigureActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mAppWidgetId = getIntent().getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
            AppWidgetManager.INVALID_APPWIDGET_ID);

    final Intent resultValue = new Intent();
    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);

    if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
        setResult(RESULT_CANCELED, resultValue);
        finish();/* w  w w .j  a v a  2s  . c o  m*/
    }

    // Create an empty adapter we will use to display the loaded data.
    mAdapter = new SimpleCursorAdapter(this, android.R.layout.select_dialog_singlechoice, null,
            new String[] { Subscribers.SUBSCRIBER_ID }, new int[] { android.R.id.text1 }, 0);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.choose_subscriber_title);

    builder.setSingleChoiceItems(mAdapter, 0, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int position) {
            final Cursor cursor = mAdapter.getCursor();
            cursor.moveToPosition(position);

            ContentValues values = new ContentValues(1);
            values.put(Settings.SUBSCRIBER, cursor.getString(SubscribersQuery.SUBSCRIBER_ID));

            ContentResolver cr = getContentResolver();
            cr.insert(Settings.buildAppWidgetUri(mAppWidgetId), values);

            mResultCode = RESULT_OK;
            setResult(mResultCode, resultValue);

            dialog.dismiss();
            finish();
        }
    });

    builder.setOnCancelListener(new OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            setResult(RESULT_CANCELED, resultValue);

            dialog.dismiss();
            finish();
        }
    });

    builder.setNegativeButton(R.string.cancel, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            dialog.cancel();
        }
    });

    mAlertDialog = builder.create();

    getSupportLoaderManager().initLoader(0, null, this);
}

From source file:com.bchalk.GVCallback.callback.GVCommunicator.java

public static void insertPlaceholderCall(ContentResolver contentResolver, String number) {
    ContentValues values = new ContentValues();
    values.put(CallLog.Calls.NUMBER, number);
    values.put(CallLog.Calls.DATE, System.currentTimeMillis());
    values.put(CallLog.Calls.DURATION, 0);
    values.put(CallLog.Calls.TYPE, CallLog.Calls.OUTGOING_TYPE);
    values.put(CallLog.Calls.NEW, 1);/*from w  w  w  . ja  va2  s  .com*/
    values.put(CallLog.Calls.CACHED_NAME, "");
    values.put(CallLog.Calls.CACHED_NUMBER_TYPE, 0);
    values.put(CallLog.Calls.CACHED_NUMBER_LABEL, "");
    Log.d(TAG, "Inserting call log placeholder for " + number);
    contentResolver.insert(CallLog.Calls.CONTENT_URI, values);
}

From source file:ca.ualberta.cmput301w14t08.geochan.fragments.ExpandImageFragment.java

/**
 * Initializes the UI of the fragment./*from  w ww  .j ava2  s .c o  m*/
 */
@Override
public void onStart() {
    super.onStart();
    ProgressDialog dialog = new ProgressDialog(getActivity());
    dialog.setMessage("Downloading Image");
    ImageView imageView = (ImageView) getView().findViewById(R.id.expanded_image);
    final Bitmap image = CacheManager.getInstance().deserializeImage(id);
    if (image == null) {
        // Start the image getter thread.
        ThreadManager.startGetImage(id, imageView, dialog);
    } else {
        imageView.setImageBitmap(image);
        ThreadManager.startGetImage(id, imageView, null);
    }
    LinearLayout rlayout = (LinearLayout) getView().findViewById(R.id.expanded_image_relative);
    rlayout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            getFragmentManager().popBackStack();
        }
    });
    Button saveButton = (Button) getView().findViewById(R.id.save_image_button);
    saveButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            ContentValues values = new ContentValues();
            values.put(Images.Media.TITLE, id);
            values.put(Images.Media.DESCRIPTION, id);
            values.put(Images.Media.MIME_TYPE, "image/jpeg");
            values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());

            Uri uri = null;
            ContentResolver contentResolver = getActivity().getContentResolver();
            try {
                uri = contentResolver.insert(Images.Media.EXTERNAL_CONTENT_URI, values);
                OutputStream imageOut = contentResolver.openOutputStream(uri);
                try {
                    image.compress(Bitmap.CompressFormat.JPEG, 90, imageOut);
                } finally {
                    imageOut.close();
                }
                Toast.makeText(getActivity(), "Saved to gallery.", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toaster.toastShort("Failed to save to gallery.");
                if (uri != null) {
                    contentResolver.delete(uri, null, null);
                    uri = null;
                }
            }
        }
    });
}