List of usage examples for android.content ContentResolver insert
public final @Nullable Uri insert(@RequiresPermission.Write @NonNull Uri url, @Nullable ContentValues values)
From source file:org.mariotaku.twidere.fragment.support.UserFragment.java
private void showRelationship(ParcelableUser user, Relationship relationship) { mRelationship = relationship;//from w w w.ja va2 s . co m if (user == null) return; invalidateOptionsMenu(); final boolean isMyself = user.account_id == user.id; if (isMyself) { mFollowButton.setText(R.string.edit); mFollowButton.setVisibility(View.VISIBLE); } else if (relationship != null) { final int drawableRes; mFollowButton.setEnabled(!relationship.isSourceBlockedByTarget()); if (relationship.isSourceBlockedByTarget()) { mPagesErrorContainer.setVisibility(View.VISIBLE); final String displayName = mUserColorNameManager.getDisplayName(user, mNameFirst, true); mPagesErrorText.setText(getString(R.string.blocked_by_user_summary, displayName)); mPagesErrorIcon.setImageResource(R.drawable.ic_info_error_generic); mPagesContent.setVisibility(View.GONE); } else if (!relationship.isSourceFollowingTarget() && user.is_protected) { mPagesErrorContainer.setVisibility(View.VISIBLE); final String displayName = mUserColorNameManager.getDisplayName(user, mNameFirst, true); mPagesErrorText.setText(getString(R.string.user_protected_summary, displayName)); mPagesErrorIcon.setImageResource(R.drawable.ic_info_locked); mPagesContent.setVisibility(View.GONE); } else { mPagesErrorContainer.setVisibility(View.GONE); mPagesErrorText.setText(null); mPagesContent.setVisibility(View.VISIBLE); } if (relationship.isSourceBlockingTarget()) { mFollowButton.setText(R.string.unblock); drawableRes = R.drawable.ic_follow_blocked; } else if (relationship.isSourceFollowingTarget()) { mFollowButton.setText(R.string.unfollow); if (relationship.isTargetFollowingSource()) { drawableRes = R.drawable.ic_follow_bidirectional; } else { drawableRes = R.drawable.ic_follow_outgoing; } } else if (user.is_follow_request_sent) { mFollowButton.setText(R.string.requested); if (relationship.isTargetFollowingSource()) { drawableRes = R.drawable.ic_follow_incoming; } else { drawableRes = R.drawable.ic_follow_pending; } } else { mFollowButton.setText(R.string.follow); if (relationship.isTargetFollowingSource()) { drawableRes = R.drawable.ic_follow_incoming; } else { drawableRes = R.drawable.ic_follow_none; } } final Drawable icon = ResourcesCompat.getDrawable(getResources(), drawableRes, null); final int iconSize = Math.round(mFollowButton.getTextSize() * 1.4f); icon.setBounds(0, 0, iconSize, iconSize); icon.setColorFilter(mFollowButton.getCurrentTextColor(), Mode.SRC_ATOP); mFollowButton.setCompoundDrawables(icon, null, null, null); mFollowButton.setCompoundDrawablePadding(Math.round(mFollowButton.getTextSize() * 0.25f)); final ContentResolver resolver = getContentResolver(); final ContentValues cachedValues = ParcelableUser.makeCachedUserContentValues(user); resolver.insert(CachedUsers.CONTENT_URI, cachedValues); mFollowButton.setVisibility(View.VISIBLE); } else { mFollowButton.setText(null); mFollowButton.setVisibility(View.GONE); mPagesErrorContainer.setVisibility(View.GONE); mPagesContent.setVisibility(View.VISIBLE); } }
From source file:org.getlantern.firetweet.fragment.support.UserFragment.java
@Override public boolean onOptionsItemSelected(final MenuItem item) { final AsyncTwitterWrapper twitter = getTwitterWrapper(); final ParcelableUser user = getUser(); final Relationship relationship = mRelationship; if (user == null || twitter == null) return false; switch (item.getItemId()) { case MENU_BLOCK: { if (mRelationship != null) { if (mRelationship.isSourceBlockingTarget()) { twitter.destroyBlockAsync(user.account_id, user.id); } else { CreateUserBlockDialogFragment.show(getFragmentManager(), user); }//from www. j av a 2 s . co m } break; } case MENU_REPORT_SPAM: { ReportSpamDialogFragment.show(getFragmentManager(), user); break; } case MENU_ADD_TO_FILTER: { final boolean filtering = Utils.isFilteringUser(getActivity(), user.id); final ContentResolver cr = getContentResolver(); if (filtering) { final Expression where = Expression.equals(Filters.Users.USER_ID, user.id); cr.delete(Filters.Users.CONTENT_URI, where.getSQL(), null); showInfoMessage(getActivity(), R.string.message_user_unmuted, false); } else { cr.insert(Filters.Users.CONTENT_URI, ContentValuesCreator.createFilteredUser(user)); showInfoMessage(getActivity(), R.string.message_user_muted, false); } break; } case MENU_MUTE_USER: { if (mRelationship != null) { if (mRelationship.isSourceMutingTarget()) { twitter.destroyMuteAsync(user.account_id, user.id); } else { CreateUserMuteDialogFragment.show(getFragmentManager(), user); } } break; } case MENU_MENTION: { final Intent intent = new Intent(INTENT_ACTION_MENTION); final Bundle bundle = new Bundle(); bundle.putParcelable(EXTRA_USER, user); intent.putExtras(bundle); startActivity(intent); break; } case MENU_SEND_DIRECT_MESSAGE: { final Uri.Builder builder = new Uri.Builder(); builder.scheme(SCHEME_FIRETWEET); builder.authority(AUTHORITY_DIRECT_MESSAGES_CONVERSATION); builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID, String.valueOf(user.account_id)); builder.appendQueryParameter(QUERY_PARAM_USER_ID, String.valueOf(user.id)); final Intent intent = new Intent(Intent.ACTION_VIEW, builder.build()); intent.putExtra(EXTRA_ACCOUNT, ParcelableCredentials.getAccount(getActivity(), user.account_id)); intent.putExtra(EXTRA_USER, user); startActivity(intent); break; } case MENU_SET_COLOR: { final Intent intent = new Intent(getActivity(), ColorPickerDialogActivity.class); intent.putExtra(EXTRA_COLOR, getUserColor(getActivity(), user.id, true)); intent.putExtra(EXTRA_ALPHA_SLIDER, false); intent.putExtra(EXTRA_CLEAR_BUTTON, true); startActivityForResult(intent, REQUEST_SET_COLOR); break; } case MENU_CLEAR_NICKNAME: { clearUserNickname(getActivity(), user.id); break; } case MENU_SET_NICKNAME: { final String nick = getUserNickname(getActivity(), user.id, true); SetUserNicknameDialogFragment.show(getFragmentManager(), user.id, nick); break; } case MENU_ADD_TO_LIST: { final Intent intent = new Intent(INTENT_ACTION_SELECT_USER_LIST); intent.setClass(getActivity(), UserListSelectorActivity.class); intent.putExtra(EXTRA_ACCOUNT_ID, user.account_id); intent.putExtra(EXTRA_SCREEN_NAME, getAccountScreenName(getActivity(), user.account_id)); startActivityForResult(intent, REQUEST_ADD_TO_LIST); break; } case MENU_OPEN_WITH_ACCOUNT: { final Intent intent = new Intent(INTENT_ACTION_SELECT_ACCOUNT); intent.setClass(getActivity(), AccountSelectorActivity.class); intent.putExtra(EXTRA_SINGLE_SELECTION, true); startActivityForResult(intent, REQUEST_SELECT_ACCOUNT); break; } case MENU_FOLLOW: { if (relationship == null) return false; final boolean isFollowing = relationship.isSourceFollowingTarget(); final boolean isCreatingFriendship = twitter.isCreatingFriendship(user.account_id, user.id); final boolean isDestroyingFriendship = twitter.isDestroyingFriendship(user.account_id, user.id); if (!isCreatingFriendship && !isDestroyingFriendship) { if (isFollowing) { DestroyFriendshipDialogFragment.show(getFragmentManager(), user); } else { twitter.createFriendshipAsync(user.account_id, user.id); } } return true; } case R.id.muted_users: { openMutesUsers(getActivity(), user.account_id); return true; } case R.id.blocked_users: { openUserBlocks(getActivity(), user.account_id); return true; } case R.id.incoming_friendships: { openIncomingFriendships(getActivity(), user.account_id); return true; } default: { if (item.getIntent() != null) { try { startActivity(item.getIntent()); } catch (final ActivityNotFoundException e) { Log.w(LOGTAG, e); return false; } } break; } } return true; }
From source file:com.vegnab.vegnab.MainVNActivity.java
void logPurchaseActivity(ContentValues cv) { // create a new record with whatever fields are provided in ContentValues Uri uri, purchUri = Uri.withAppendedPath(ContentProvider_VegNab.CONTENT_URI, "purchases"); ContentResolver rs = getContentResolver(); // create a new record uri = rs.insert(purchUri, cv); mNewPurcRecId = Long.parseLong(uri.getLastPathSegment()); if (LDebug.ON) Log.d(LOG_TAG, "mNewPurcRecId of new record stored in DB: " + mNewPurcRecId); }
From source file:com.dwdesign.tweetings.fragment.UserProfileFragment.java
@Override public boolean onMenuItemClick(final MenuItem item) { if (mUser == null || mService == null) return false; switch (item.getItemId()) { case MENU_TAKE_PHOTO: { takePhoto();/* w ww . j ava 2s . co m*/ break; } case MENU_ADD_IMAGE: { pickImage(); break; } case MENU_BANNER_TAKE_PHOTO: { takeBannerPhoto(); break; } case MENU_BANNER_ADD_IMAGE: { pickBannerImage(); break; } case MENU_TRACKING: { UpdateTrackingTask task = new UpdateTrackingTask(!tracking); task.execute(); break; } case MENU_BLOCK: { if (mService == null || mFriendship == null) { break; } if (mFriendship.isSourceBlockingTarget()) { mService.destroyBlock(mAccountId, mUser.getId()); } else { mService.createBlock(mAccountId, mUser.getId()); } break; } case MENU_REPORT_SPAM: { mService.reportSpam(mAccountId, mUser.getId()); break; } case MENU_MUTE_USER: { final String screen_name = mUser.getScreenName(); final Uri uri = Filters.Users.CONTENT_URI; final ContentValues values = new ContentValues(); final SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).edit(); final ContentResolver resolver = getContentResolver(); values.put(Filters.Users.TEXT, screen_name); resolver.delete(uri, Filters.Users.TEXT + " = '" + screen_name + "'", null); resolver.insert(uri, values); editor.putBoolean(PREFERENCE_KEY_ENABLE_FILTER, true).commit(); Toast.makeText(getActivity(), R.string.user_muted, Toast.LENGTH_SHORT).show(); break; } case MENU_MENTION: { final Intent intent = new Intent(INTENT_ACTION_COMPOSE); final Bundle bundle = new Bundle(); final String name = mUser.getName(); final String screen_name = mUser.getScreenName(); bundle.putLong(INTENT_KEY_ACCOUNT_ID, mAccountId); bundle.putString(INTENT_KEY_TEXT, "@" + screen_name + " "); bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, screen_name); bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, name); intent.putExtras(bundle); startActivity(intent); break; } case MENU_SEND_DIRECT_MESSAGE: { final Uri.Builder builder = new Uri.Builder(); builder.scheme(SCHEME_TWEETINGS); builder.authority(AUTHORITY_DIRECT_MESSAGES_CONVERSATION); builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID, String.valueOf(mAccountId)); builder.appendQueryParameter(QUERY_PARAM_CONVERSATION_ID, String.valueOf(mUser.getId())); startActivity(new Intent(Intent.ACTION_VIEW, builder.build())); break; } case MENU_VIEW_ON_TWITTER: { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://twitter.com/" + mUser.getScreenName())); startActivity(browserIntent); break; } case MENU_WANT_RETWEETS: { updateFriendship(); break; } case MENU_EXTENSIONS: { final Intent intent = new Intent(INTENT_ACTION_EXTENSION_OPEN_USER); final Bundle extras = new Bundle(); extras.putParcelable(INTENT_KEY_USER, new ParcelableUser(mUser, mAccountId)); intent.putExtras(extras); startActivity(Intent.createChooser(intent, getString(R.string.open_with_extensions))); break; } case MENU_SET_COLOR: { final Intent intent = new Intent(INTENT_ACTION_SET_COLOR); startActivityForResult(intent, REQUEST_SET_COLOR); break; } case MENU_CLEAR_COLOR: { clearUserColor(getActivity(), mUserId); updateUserColor(); break; } } return true; }
From source file:org.cryptsecure.Utility.java
/** * Stores an image in the gallery. This is a fixed version that stores * correct DATE_TAKEN so that the ordering of remains correct. * /*from w w w . ja v a 2 s. co m*/ * @see android.provider.MediaStore.Images.Media#insertImage(ContentResolver, * Bitmap, String, String) */ public static final String insertImage(ContentResolver contentResolver, Bitmap bitmap, String title, String description) { final int SAVEQUALITY = 100; ContentValues values = new ContentValues(); values.put(Images.Media.TITLE, title); values.put(Images.Media.DISPLAY_NAME, title); values.put(Images.Media.DESCRIPTION, description); values.put(Images.Media.MIME_TYPE, "image/jpeg"); // Fix values.put(Images.Media.DATE_ADDED, System.currentTimeMillis()); values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis()); Uri url = null; String returnValue = null; boolean ok = false; try { url = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); if (bitmap != null) { OutputStream outputStream = contentResolver.openOutputStream(url); try { bitmap.compress(Bitmap.CompressFormat.JPEG, SAVEQUALITY, outputStream); ok = true; } catch (Exception e) { // ignore } outputStream.close(); } } catch (Exception e) { // ignore } if (!ok) { // If something went wrong, delete the entry if (url != null) { contentResolver.delete(url, null, null); url = null; } } if (url != null) { returnValue = url.toString(); } return returnValue; }
From source file:dev.dworks.apps.anexplorer.fragment.DirectoryFragment.java
public void onUserModeChanged() { final ContentResolver resolver = getActivity().getContentResolver(); final State state = getDisplayState(this); final RootInfo root = getArguments().getParcelable(EXTRA_ROOT); final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC); if (root != null && doc != null) { final Uri stateUri = RecentsProvider.buildState(root.authority, root.rootId, doc.documentId); final ContentValues values = new ContentValues(); values.put(StateColumns.MODE, state.userMode); new AsyncTask<Void, Void, Void>() { @Override/*from w w w . ja va 2s . c o m*/ protected Void doInBackground(Void... params) { resolver.insert(stateUri, values); return null; } }.execute(); } // Mode change is just visual change; no need to kick loader, and // deliver change event immediately. state.derivedMode = state.userMode; ((DocumentsActivity) getActivity()).onStateChanged(); updateDisplayState(); }
From source file:org.mariotaku.twidere.fragment.support.UserFragment.java
@Override public boolean onOptionsItemSelected(final MenuItem item) { final AsyncTwitterWrapper twitter = getTwitterWrapper(); final ParcelableUser user = getUser(); final Relationship relationship = mRelationship; if (user == null || twitter == null) return false; switch (item.getItemId()) { case MENU_BLOCK: { if (mRelationship != null) { if (mRelationship.isSourceBlockingTarget()) { twitter.destroyBlockAsync(user.account_id, user.id); } else { CreateUserBlockDialogFragment.show(getFragmentManager(), user); }// www .java 2 s . co m } break; } case MENU_REPORT_SPAM: { ReportSpamDialogFragment.show(getFragmentManager(), user); break; } case MENU_ADD_TO_FILTER: { final boolean filtering = Utils.isFilteringUser(getActivity(), user.id); final ContentResolver cr = getContentResolver(); if (filtering) { final Expression where = Expression.equals(Filters.Users.USER_ID, user.id); cr.delete(Filters.Users.CONTENT_URI, where.getSQL(), null); Utils.showInfoMessage(getActivity(), R.string.message_user_unmuted, false); } else { cr.insert(Filters.Users.CONTENT_URI, ContentValuesCreator.createFilteredUser(user)); Utils.showInfoMessage(getActivity(), R.string.message_user_muted, false); } break; } case MENU_MUTE_USER: { if (mRelationship != null) { if (mRelationship.isSourceMutingTarget()) { twitter.destroyMuteAsync(user.account_id, user.id); } else { CreateUserMuteDialogFragment.show(getFragmentManager(), user); } } break; } case MENU_MENTION: { final Intent intent = new Intent(INTENT_ACTION_MENTION); final Bundle bundle = new Bundle(); bundle.putParcelable(EXTRA_USER, user); intent.putExtras(bundle); startActivity(intent); break; } case MENU_SEND_DIRECT_MESSAGE: { final Uri.Builder builder = new Uri.Builder(); builder.scheme(SCHEME_TWIDERE); builder.authority(AUTHORITY_DIRECT_MESSAGES_CONVERSATION); builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID, String.valueOf(user.account_id)); builder.appendQueryParameter(QUERY_PARAM_USER_ID, String.valueOf(user.id)); final Intent intent = new Intent(Intent.ACTION_VIEW, builder.build()); intent.putExtra(EXTRA_ACCOUNT, ParcelableCredentials.getAccount(getActivity(), user.account_id)); intent.putExtra(EXTRA_USER, user); startActivity(intent); break; } case MENU_SET_COLOR: { final Intent intent = new Intent(getActivity(), ColorPickerDialogActivity.class); intent.putExtra(EXTRA_COLOR, mUserColorNameManager.getUserColor(user.id, true)); intent.putExtra(EXTRA_ALPHA_SLIDER, false); intent.putExtra(EXTRA_CLEAR_BUTTON, true); startActivityForResult(intent, REQUEST_SET_COLOR); break; } case MENU_CLEAR_NICKNAME: { final UserColorNameManager manager = UserColorNameManager.getInstance(getActivity()); manager.clearUserNickname(user.id); break; } case MENU_SET_NICKNAME: { final String nick = mUserColorNameManager.getUserNickname(user.id, true); SetUserNicknameDialogFragment.show(getFragmentManager(), user.id, nick); break; } case MENU_ADD_TO_LIST: { final Intent intent = new Intent(INTENT_ACTION_SELECT_USER_LIST); intent.setClass(getActivity(), UserListSelectorActivity.class); intent.putExtra(EXTRA_ACCOUNT_ID, user.account_id); intent.putExtra(EXTRA_SCREEN_NAME, Utils.getAccountScreenName(getActivity(), user.account_id)); startActivityForResult(intent, REQUEST_ADD_TO_LIST); break; } case MENU_OPEN_WITH_ACCOUNT: { final Intent intent = new Intent(INTENT_ACTION_SELECT_ACCOUNT); intent.setClass(getActivity(), AccountSelectorActivity.class); intent.putExtra(EXTRA_SINGLE_SELECTION, true); startActivityForResult(intent, REQUEST_SELECT_ACCOUNT); break; } case MENU_FOLLOW: { if (relationship == null) return false; final boolean isFollowing = relationship.isSourceFollowingTarget(); final boolean isCreatingFriendship = twitter.isCreatingFriendship(user.account_id, user.id); final boolean isDestroyingFriendship = twitter.isDestroyingFriendship(user.account_id, user.id); if (!isCreatingFriendship && !isDestroyingFriendship) { if (isFollowing) { DestroyFriendshipDialogFragment.show(getFragmentManager(), user); } else { twitter.createFriendshipAsync(user.account_id, user.id); } } return true; } case MENU_ENABLE_RETWEETS: { final boolean newState = !item.isChecked(); final FriendshipUpdate update = new FriendshipUpdate(); update.retweets(newState); twitter.updateFriendship(user.account_id, user.id, update); item.setChecked(newState); return true; } case R.id.muted_users: { Utils.openMutesUsers(getActivity(), user.account_id); return true; } case R.id.blocked_users: { Utils.openUserBlocks(getActivity(), user.account_id); return true; } case R.id.incoming_friendships: { Utils.openIncomingFriendships(getActivity(), user.account_id); return true; } case R.id.user_mentions: { Utils.openUserMentions(getActivity(), user.account_id, user.screen_name); return true; } case R.id.saved_searches: { Utils.openSavedSearches(getActivity(), user.account_id); return true; } default: { if (item.getIntent() != null) { try { startActivity(item.getIntent()); } catch (final ActivityNotFoundException e) { Log.w(LOGTAG, e); return false; } } break; } } return true; }
From source file:net.niyonkuru.koodroid.html.SubscribersHandler.java
@Override public ArrayList<ContentProviderOperation> parse(Document doc, ContentResolver resolver) throws HandlerException { final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); Element subscriberLi = doc.select("div#banSelector li:has(div)").first(); while (subscriberLi != null) { String text = subscriberLi.text(); /* this assumes the name and phone number are separated by a space */ int separator = text.lastIndexOf(' ') + 1; String subscriberId = text.substring(separator).replaceAll("\\D", ""); if (subscriberId.length() != 10) throw new HandlerException(getString(R.string.parser_error_unexpected_input)); final ContentProviderOperation.Builder builder; final Uri subscriberUri = Subscribers.buildSubscriberUri(subscriberId); if (subscriberExists(subscriberUri, resolver)) { builder = ContentProviderOperation.newUpdate(subscriberUri); builder.withValue(Subscribers.UPDATED, System.currentTimeMillis()); } else {/* w ww . j a v a 2 s .c o m*/ builder = ContentProviderOperation.newInsert(Subscribers.CONTENT_URI); } builder.withValue(Subscribers.SUBSCRIBER_ID, subscriberId); String fullName = ""; String[] names = text.substring(0, separator).split("\\s"); for (String name : names) { fullName += ParserUtils.capitalize(name) + " "; } builder.withValue(Subscribers.SUBSCRIBER_FULL_NAME, fullName.trim()); if (subscriberLi.hasAttr("onClick")) { String switchUrl = subscriberLi.attr("onClick"); /* extract only the url */ switchUrl = switchUrl.substring(switchUrl.indexOf('/'), switchUrl.lastIndexOf('\'')); builder.withValue(Subscribers.SUBSCRIBER_SWITCHER, switchUrl); } else { /* this is the default subscriber as it doesn't have a switcher url */ ContentValues cv = new ContentValues(1); cv.put(Settings.SUBSCRIBER, subscriberId); resolver.insert(Settings.CONTENT_URI, cv); } builder.withValue(Subscribers.SUBSCRIBER_EMAIL, mParent); batch.add(builder.build()); subscriberLi = subscriberLi.nextElementSibling(); } if (batch.size() == 0) throw new HandlerException(getString(R.string.parser_error_unexpected_input)); JSONObject metadata = new JSONObject(); try { metadata.put("subscribers", batch.size()); metadata.put("language", getString(R.string.locale)); } catch (JSONException ignored) { } Crittercism.setMetadata(metadata); Crittercism.setUsername(mParent); return batch; }
From source file:com.karura.framework.plugins.Capture.java
/** * Called when the video view exits.//from w ww . j av a 2 s . co m * * @param requestCode * The request code originally supplied to startActivityForResult(), allowing you to identify who this * result came from. * @param resultCode * The integer result code returned by the child activity through its setResult(). * @param intent * An Intent, which can return result data to the caller (various data can be attached to Intent * "extras"). * @throws JSONException */ public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { final String callId = requestCallIdMap.get(requestCode); final ContentResolver cr = getContext().getContentResolver(); if (callId == null) { return; } requestCallIdMap.remove(requestCode); runInBackground(new Runnable() { public void run() { // Result received okay if (resultCode == Activity.RESULT_OK) { // An audio clip was requested if (requestCode == CAPTURE_AUDIO) { // Get the uri of the audio clip Uri data = intent.getData(); // create a file object from the uri results.put(createMediaFile(data)); // Send Uri back to JavaScript for listening to audio resolveWithResult(callId, results); } else if (requestCode == CAPTURE_IMAGE) { // For some reason if I try to do: // Uri data = intent.getData(); // It crashes in the emulator and on my phone with a null pointer exception // To work around it I had to grab the code from CameraLauncher.java try { // Create entry in media store for image // (Don't use insertImage() because it uses default compression setting of 50 - no way to // change it) ContentValues values = new ContentValues(); values.put(MIME_TYPE, IMAGE_JPEG); Uri uri = null; try { uri = cr.insert(EXTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException e) { Log.d(LOG_TAG, "Can't write to external media storage."); try { uri = cr.insert(INTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException ex) { Log.d(LOG_TAG, "Can't write to internal media storage."); reject(callId, CAPTURE_INTERNAL_ERR, "Error capturing image - no media storage found."); return; } } FileInputStream fis = new FileInputStream( DirectoryManager.getTempDirectoryPath(getContext()) + "/Capture.jpg"); OutputStream os = cr.openOutputStream(uri); byte[] buffer = new byte[4096]; int len; while ((len = fis.read(buffer)) != -1) { os.write(buffer, 0, len); } os.flush(); os.close(); fis.close(); // Add image to results results.put(createMediaFile(uri)); checkForDuplicateImage(); // Send Uri back to JavaScript for viewing image resolveWithResult(callId, results); } catch (IOException e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } reject(callId, CAPTURE_INTERNAL_ERR, "Error capturing image."); } } else if (requestCode == CAPTURE_VIDEO) { // Get the uri of the video clip Uri data = intent.getData(); // create a file object from the uri results.put(createMediaFile(data)); // Send Uri back to JavaScript for viewing video resolveWithResult(callId, results); } } // if cancelled or something else else { // user canceled the action rejectWithError(callId, CAPTURE_NO_MEDIA_FILES, "Canceled."); } } }); }
From source file:com.nextgis.ngm_clink_monitoring.fragments.CreateObjectFragment.java
protected void writePhotoAttach(File tempPhotoFile) throws IOException { GISApplication app = (GISApplication) getActivity().getApplication(); ContentResolver contentResolver = app.getContentResolver(); String photoFileName = getPhotoFileName(tempPhotoFile); Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), photoFileName: " + photoFileName); Uri allAttachesUri = Uri.parse("content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + mObjectLayerName + "/" + mObjectId + "/attach"); Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), allAttachesUri: " + allAttachesUri); ContentValues values = new ContentValues(); values.put(VectorLayer.ATTACH_DISPLAY_NAME, photoFileName); values.put(VectorLayer.ATTACH_MIME_TYPE, "image/jpeg"); //values.put(VectorLayer.ATTACH_DESCRIPTION, photoFileName); Uri attachUri = null;/*from w w w . j a va 2 s .c o m*/ String insertAttachError = null; try { attachUri = contentResolver.insert(allAttachesUri, values); Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), insert: " + attachUri.toString()); } catch (Exception e) { Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), Insert attach failed: " + e.getLocalizedMessage()); insertAttachError = "Insert attach failed: " + e.getLocalizedMessage(); } if (null != attachUri) { int exifOrientation = BitmapUtil.getOrientationFromExif(tempPhotoFile); // resize and rotate Bitmap sourceBitmap = BitmapFactory.decodeFile(tempPhotoFile.getPath()); Bitmap resizedBitmap = BitmapUtil.getResizedBitmap(sourceBitmap, FoclConstants.PHOTO_MAX_SIZE_PX, FoclConstants.PHOTO_MAX_SIZE_PX); Bitmap rotatedBitmap = BitmapUtil.rotateBitmap(resizedBitmap, exifOrientation); // jpeg compress File tempAttachFile = File.createTempFile("attach", null, app.getCacheDir()); OutputStream tempOutStream = new FileOutputStream(tempAttachFile); rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, FoclConstants.PHOTO_JPEG_COMPRESS_QUALITY, tempOutStream); tempOutStream.close(); int newHeight = rotatedBitmap.getHeight(); int newWidth = rotatedBitmap.getWidth(); rotatedBitmap.recycle(); // write EXIF to new file BitmapUtil.copyExifData(tempPhotoFile, tempAttachFile); BitmapUtil.writeLocationToExif(tempAttachFile, mAccurateLocation, app.getGpsTimeOffset()); ExifInterface attachExif = new ExifInterface(tempAttachFile.getCanonicalPath()); attachExif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + ExifInterface.ORIENTATION_NORMAL); attachExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, "" + newHeight); attachExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, "" + newWidth); attachExif.saveAttributes(); // attach data from tempAttachFile OutputStream attachOutStream = contentResolver.openOutputStream(attachUri); if (attachOutStream != null) { FoclFileUtil.copy(new FileInputStream(tempAttachFile), attachOutStream); attachOutStream.close(); } else { Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), attachOutStream == null, attachUri" + attachUri.toString()); } if (!tempAttachFile.delete()) { Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), tempAttachFile.delete() failed, tempAttachFile:" + tempAttachFile.getAbsolutePath()); } } if (app.isOriginalPhotoSaving()) { BitmapUtil.writeLocationToExif(tempPhotoFile, mAccurateLocation, app.getGpsTimeOffset()); File origPhotoFile = new File(getDailyPhotoFolder(), photoFileName); if (!com.nextgis.maplib.util.FileUtil.move(tempPhotoFile, origPhotoFile)) { Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), move original failed, tempPhotoFile:" + tempPhotoFile.getAbsolutePath() + ", origPhotoFile: " + origPhotoFile.getAbsolutePath()); throw new IOException( "Save original photo failed, tempPhotoFile: " + tempPhotoFile.getAbsolutePath()); } } else { if (!tempPhotoFile.delete()) { Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), tempPhotoFile.delete() failed, tempPhotoFile:" + tempPhotoFile.getAbsolutePath()); } } if (null != insertAttachError) { throw new IOException(insertAttachError); } }