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:com.andrew.apollo.utils.MusicUtils.java
/** * @param context The {@link Context} to use. * @param name The name of the new playlist. * @return A new playlist ID.//from w w w.ja va 2 s .com */ public static long createPlaylist(final Context context, final String name) { long result = -1; if (name != null && name.length() > 0) { final ContentResolver resolver = context.getContentResolver(); final String[] projection = new String[] { PlaylistsColumns.NAME }; final String selection = PlaylistsColumns.NAME + " = ?"; Cursor cursor = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection, selection, new String[] { name }, null); if (cursor != null && cursor.getCount() <= 0) { final ContentValues values = new ContentValues(1); values.put(PlaylistsColumns.NAME, name); final Uri uri = resolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, values); if (uri != null) { result = Long.parseLong(uri.getLastPathSegment()); } } if (cursor != null) { cursor.close(); } } return result; }
From source file:p1.nd.khan.jubair.mohammadd.popularmovies.adapter.MovieDetailsAdapter.java
/** * Method to check if movie is favorite. * * @param movieId to check./*w ww .j a v a 2 s .co m*/ * @return movie title after addition else null */ private String addToFavorites(int movieId) { String title = null; String[] projection = new String[] { "*" }; String selection = MovieEntry.C_MOVIE_ID + "=?"; String[] selectionArgs = { String.valueOf(movieId) }; ContentResolver contentResolver = mContext.getContentResolver(); Cursor cMovies = null; Cursor cTrailers = null; Cursor cReviews = null; try { cMovies = contentResolver.query(MovieEntry.CONTENT_URI, projection, selection, selectionArgs, null); if (null != cMovies && cMovies.moveToFirst()) { ContentValues contentValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cMovies, contentValues); contentValues.remove("_id"); title = contentValues.getAsString(MovieEntry.C_ORIGINAL_TITLE); contentResolver.insert(MovieEntry.FAVORITES_CONTENT_URI, contentValues); } cTrailers = contentResolver.query(TrailersEntry.CONTENT_URI, projection, selection, selectionArgs, null); while (null != cTrailers && cTrailers.moveToNext()) { ContentValues contentValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cTrailers, contentValues); contentValues.remove("_id"); contentResolver.insert(TrailersEntry.FAVORITES_CONTENT_URI, contentValues); } cReviews = contentResolver.query(ReviewsEntry.CONTENT_URI, projection, selection, selectionArgs, null); while (null != cReviews && cReviews.moveToNext()) { ContentValues contentValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cReviews, contentValues); contentValues.remove("_id"); contentResolver.insert(ReviewsEntry.FAVORITES_CONTENT_URI, contentValues); } } catch (SQLException e) { Log.e(LOG_TAG, "SQLException!"); } finally { if (null != cMovies) cMovies.close(); if (null != cTrailers) cTrailers.close(); if (null != cReviews) cReviews.close(); } return title; }
From source file:ca.frozen.curlingtv.classes.Utils.java
public static String saveImage(ContentResolver contentResolver, Bitmap source, String title, String description) {//from ww w .j a v a 2 s . com File snapshot = null; Uri url = null; try { // get/create the snapshots folder File pictures = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File rpi = new File(pictures, App.getStr(R.string.app_name)); if (!rpi.exists()) { rpi.mkdir(); } // save the file within the snapshots folder snapshot = new File(rpi, title); OutputStream stream = new FileOutputStream(snapshot); source.compress(Bitmap.CompressFormat.JPEG, 90, stream); stream.flush(); stream.close(); // create the content values ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, title); values.put(MediaStore.Images.Media.DISPLAY_NAME, title); if (description != null) { values.put(MediaStore.Images.Media.DESCRIPTION, description); } values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis()); values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(MediaStore.Images.ImageColumns.BUCKET_ID, snapshot.toString().toLowerCase(Locale.US).hashCode()); values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, snapshot.getName().toLowerCase(Locale.US)); values.put("_data", snapshot.getAbsolutePath()); // insert the image into the database url = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (Exception ex) { return null; } // return the URL return (url != null) ? url.toString() : null; }
From source file:com.tct.mail.providers.Attachment.java
/** * Constructor for use when creating attachments in eml files. *///ww w . j a v a 2 s .com public Attachment(Context context, Part part, Uri emlFileUri, String messageId, String cid, boolean inline, String subject) { try { // Transfer fields from mime format to provider format final String contentTypeHeader = MimeUtility.unfoldAndDecode(part.getContentType()); name = MimeUtility.getHeaderParameter(contentTypeHeader, "name"); if (name == null) { final String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition()); name = MimeUtility.getHeaderParameter(contentDisposition, "filename"); } //TS: Gantao 2016-01-13 EMAIL BUGFIX_1292212 MOD_S //If we still don't get eml files's name , set it as subject+.eml if (name == null && MimeUtility.isEmlMimeType(part.getMimeType())) { name = subject + ".eml"; } //TS: Gantao 2016-01-13 EMAIL BUGFIX_1292212 MOD_E contentType = MimeType.inferMimeType(name, part.getMimeType()); //TS: Gantao 2015-07-03 EMAIL BUGFIX_957636 MOD_S if (inline) { // TS: Gantao 2015-09-19 EMAIL BUGFIX_570084 ADD_S isInline = 1; // TS: Gantao 2015-09-19 EMAIL BUGFIX_570084 ADD_E uri = EmlAttachmentProvider.getAttachmentByCidUri(emlFileUri, messageId); uri = uri.buildUpon().appendPath(cid).build(); } else { // TS: Gantao 2015-09-19 EMAIL BUGFIX_570084 ADD_S isInline = 0; // TS: Gantao 2015-09-19 EMAIL BUGFIX_570084 ADD_E uri = EmlAttachmentProvider.getAttachmentUri(emlFileUri, messageId, cid); } //TS: Gantao 2015-07-03 EMAIL BUGFIX_957636 MOD_S contentUri = uri; thumbnailUri = uri; previewIntentUri = null; state = AttachmentState.SAVED; providerData = null; supportsDownloadAgain = false; destination = AttachmentDestination.CACHE; type = inline ? AttachmentType.INLINE_CURRENT_MESSAGE : AttachmentType.STANDARD; partId = cid; flags = 0; //TS: zhonghua.tuo 2015-3-3 EMAIL BUGFIX_936728 ADD_S realUri = null; //TS: zhonghua.tuo 2015-3-3 EMAIL BUGFIX_936728 ADD_E // insert attachment into content provider so that we can open the file final ContentResolver resolver = context.getContentResolver(); resolver.insert(uri, toContentValues()); // save the file in the cache try { final InputStream in = part.getBody().getInputStream(); final OutputStream out = resolver.openOutputStream(uri, "rwt"); size = IOUtils.copy(in, out); downloadedSize = size; in.close(); out.close(); } catch (FileNotFoundException e) { LogUtils.e(LOG_TAG, e, "Error in writing attachment to cache"); } catch (IOException e) { LogUtils.e(LOG_TAG, e, "Error in writing attachment to cache"); } // perform a second insert to put the updated size and downloaded size values in resolver.insert(uri, toContentValues()); } catch (MessagingException e) { LogUtils.e(LOG_TAG, e, "Error parsing eml attachment"); } }
From source file:info.guardianproject.otr.app.im.app.ContactListActivity.java
void clearConnectionStatus() { ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(3); values.put(Imps.AccountStatus.ACCOUNT, mAccountId); values.put(Imps.AccountStatus.PRESENCE_STATUS, Imps.Presence.OFFLINE); values.put(Imps.AccountStatus.CONNECTION_STATUS, Imps.ConnectionStatus.OFFLINE); // insert on the "account_status" uri actually replaces the existing value cr.insert(Imps.AccountStatus.CONTENT_URI, values); }
From source file:com.akop.bach.parser.PsnParser.java
private void parseAccountSummary(PsnAccount account) throws ParserException, IOException { ContentValues cv = parseSummaryData(account); ContentResolver cr = mContext.getContentResolver(); long accountId = account.getId(); boolean newRecord = true; long started = System.currentTimeMillis(); Cursor c = cr.query(Profiles.CONTENT_URI, new String[] { Profiles._ID }, Profiles.ACCOUNT_ID + "=" + accountId, null, null); if (c != null) { if (c.moveToFirst()) newRecord = false;//w ww .j ava 2 s. com c.close(); } if (newRecord) { cv.put(Profiles.ACCOUNT_ID, account.getId()); cv.put(Profiles.UUID, account.getUuid()); cr.insert(Profiles.CONTENT_URI, cv); } else { cr.update(Profiles.CONTENT_URI, cv, Profiles.ACCOUNT_ID + "=" + accountId, null); } cr.notifyChange(Profiles.CONTENT_URI, null); if (App.getConfig().logToConsole()) displayTimeTaken("Summary update", started); account.refresh(Preferences.get(mContext)); account.setOnlineId(cv.getAsString(Profiles.ONLINE_ID)); account.setIconUrl(cv.getAsString(Profiles.ICON_URL)); account.setLastSummaryUpdate(System.currentTimeMillis()); account.save(Preferences.get(mContext)); }
From source file:com.bt.download.android.gui.Librarian.java
private void syncApplicationsProviderSupport() { try {/*ww w . j a v a2s. c o m*/ List<FileDescriptor> fds = Librarian.instance().getFiles(Constants.FILE_TYPE_APPLICATIONS, 0, Integer.MAX_VALUE, false); int packagesSize = fds.size(); String[] packages = new String[packagesSize]; for (int i = 0; i < packagesSize; i++) { packages[i] = fds.get(i).album; } Arrays.sort(packages); List<ApplicationInfo> applications = context.getPackageManager().getInstalledApplications(0); int size = applications.size(); ArrayList<String> newPackagesList = new ArrayList<String>(size); for (int i = 0; i < size; i++) { ApplicationInfo appInfo = applications.get(i); try { if (appInfo == null) { continue; } newPackagesList.add(appInfo.packageName); File f = new File(appInfo.sourceDir); if (!f.canRead()) { continue; } int index = Arrays.binarySearch(packages, appInfo.packageName); if (index >= 0) { continue; } String data = appInfo.sourceDir; String title = appInfo.packageName; String packageName = appInfo.packageName; String version = ""; Apk apk = new Apk(context, appInfo.sourceDir); String[] result = parseApk(apk); if (result != null) { if (result[1] == null) { continue; } title = result[1]; version = result[0]; } ContentValues cv = new ContentValues(); cv.put(ApplicationsColumns.DATA, data); cv.put(ApplicationsColumns.SIZE, f.length()); cv.put(ApplicationsColumns.TITLE, title); cv.put(ApplicationsColumns.MIME_TYPE, Constants.MIME_TYPE_ANDROID_PACKAGE_ARCHIVE); cv.put(ApplicationsColumns.VERSION, version); cv.put(ApplicationsColumns.PACKAGE_NAME, packageName); ContentResolver cr = context.getContentResolver(); Uri uri = cr.insert(Applications.Media.CONTENT_URI, cv); if (appInfo.icon != 0) { try { InputStream is = null; OutputStream os = null; try { is = apk.openRawResource(appInfo.icon); os = cr.openOutputStream(uri); byte[] buff = new byte[4 * 1024]; int n = 0; while ((n = is.read(buff, 0, buff.length)) != -1) { os.write(buff, 0, n); } } finally { if (os != null) { os.close(); } if (is != null) { is.close(); } } } catch (Throwable e) { Log.e(TAG, "Can't retrieve icon image for application " + appInfo.packageName); } } } catch (Throwable e) { Log.e(TAG, "Error retrieving information for application " + appInfo.packageName); } } // clean uninstalled applications String[] newPackages = newPackagesList.toArray(new String[0]); Arrays.sort(newPackages); // simple way n * log(n) for (int i = 0; i < packagesSize; i++) { String packageName = packages[i]; if (Arrays.binarySearch(newPackages, packageName) < 0) { ContentResolver cr = context.getContentResolver(); cr.delete(Applications.Media.CONTENT_URI, ApplicationsColumns.PACKAGE_NAME + " LIKE '%" + packageName + "%'", null); } } } catch (Throwable e) { Log.e(TAG, "Error performing initial applications provider synchronization with device", e); } }
From source file:com.tcm.sunshine.app.FetchWeatherTask.java
/** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city//from www . ja va 2s . c om * @param lon the longitude of the city * @return the row ID of the added location. */ long addLocation(String locationSetting, String cityName, double lat, double lon) { // Students: First, check if the location with this city name exists in the db // If it exists, return the current ID // Otherwise, insert it using the content resolver and the base URI ContentResolver contentResolver = mContext.getContentResolver(); Cursor cursor = contentResolver.query(LocationEntry.CONTENT_URI, new String[] { LocationEntry._ID }, LocationEntry.COLUMN_CITY_NAME + " = ?", new String[] { cityName }, null); try { if (cursor.moveToFirst()) { return cursor.getInt(cursor.getColumnIndex(LocationEntry._ID)); } } finally { cursor.close(); } ContentValues contentValues = new ContentValues(); contentValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); contentValues.put(LocationEntry.COLUMN_CITY_NAME, cityName); contentValues.put(LocationEntry.COLUMN_COORD_LAT, lat); contentValues.put(LocationEntry.COLUMN_COORD_LONG, lon); Uri insertUri = contentResolver.insert(LocationEntry.CONTENT_URI, contentValues); return ContentUris.parseId(insertUri); }
From source file:com.ichi2.anki.tests.ContentProviderTest.java
/** * Check that inserting a new model works as expected *///ww w . j ava 2s . c o m public void testInsertAndUpdateModel() throws Exception { final ContentResolver cr = getContext().getContentResolver(); ContentValues cv = new ContentValues(); // Insert a new model cv.put(FlashCardsContract.Model.NAME, TEST_MODEL_NAME); cv.put(FlashCardsContract.Model.FIELD_NAMES, Utils.joinFields(TEST_MODEL_FIELDS)); cv.put(FlashCardsContract.Model.NUM_CARDS, TEST_MODEL_CARDS.length); cv.put(FlashCardsContract.Model.CSS, TEST_MODEL_CSS); Uri modelUri = cr.insert(FlashCardsContract.Model.CONTENT_URI, cv); assertNotNull("Check inserted model isn't null", modelUri); long mid = Long.parseLong(modelUri.getLastPathSegment()); final Collection col = CollectionHelper.getInstance().getCol(getContext()); try { JSONObject model = col.getModels().get(mid); assertEquals("Check model name", TEST_MODEL_NAME, model.getString("name")); assertEquals("Check css", TEST_MODEL_CSS, model.getString("css")); assertEquals("Check templates length", TEST_MODEL_CARDS.length, model.getJSONArray("tmpls").length()); assertEquals("Check field length", TEST_MODEL_FIELDS.length, model.getJSONArray("flds").length()); JSONArray flds = model.getJSONArray("flds"); for (int i = 0; i < flds.length(); i++) { assertEquals("Check name of fields", flds.getJSONObject(i).getString("name"), TEST_MODEL_FIELDS[i]); } // Update each of the templates in the model for (int i = 0; i < TEST_MODEL_CARDS.length; i++) { cv = new ContentValues(); cv.put(FlashCardsContract.CardTemplate.NAME, TEST_MODEL_CARDS[i]); cv.put(FlashCardsContract.CardTemplate.QUESTION_FORMAT, TEST_MODEL_QFMT[i]); cv.put(FlashCardsContract.CardTemplate.ANSWER_FORMAT, TEST_MODEL_AFMT[i]); cv.put(FlashCardsContract.CardTemplate.BROWSER_QUESTION_FORMAT, TEST_MODEL_QFMT[i]); cv.put(FlashCardsContract.CardTemplate.BROWSER_ANSWER_FORMAT, TEST_MODEL_AFMT[i]); Uri tmplUri = Uri.withAppendedPath(Uri.withAppendedPath(modelUri, "templates"), Integer.toString(i)); assertTrue("Update rows", cr.update(tmplUri, cv, null, null) > 0); JSONObject template = col.getModels().get(mid).getJSONArray("tmpls").getJSONObject(i); assertEquals("Check template name", TEST_MODEL_CARDS[i], template.getString("name")); assertEquals("Check qfmt", TEST_MODEL_QFMT[i], template.getString("qfmt")); assertEquals("Check afmt", TEST_MODEL_AFMT[i], template.getString("afmt")); assertEquals("Check bqfmt", TEST_MODEL_QFMT[i], template.getString("bqfmt")); assertEquals("Check bafmt", TEST_MODEL_AFMT[i], template.getString("bafmt")); } } finally { // Delete the model (this will force a full-sync) try { col.modSchema(false); col.getModels().rem(col.getModels().get(mid)); } catch (ConfirmModSchemaException e) { // This will never happen throw new IllegalStateException("Unexpected ConfirmModSchemaException trying to remove model"); } } }
From source file:org.deviceconnect.android.deviceplugin.theta.fragment.ThetaVRModeFragment.java
/** * Save ScreenShot.//from w ww . ja va2 s . c o m */ private void saveScreenShot() { FileManager fileManager = new FileManager(getActivity()); fileManager.checkWritePermission(new FileManager.CheckPermissionCallback() { @Override public void onSuccess() { Activity activity = getActivity(); if (activity != null && !ThetaObjectStorage.hasEnoughStorageSize()) { if (mProgress != null) { mProgress.dismiss(); mProgress = null; } // Check Android Storage Limit activity.runOnUiThread(new Runnable() { @Override public void run() { ThetaDialogFragment.showAlert(getActivity(), getResources().getString(R.string.theta_ssid_prefix), getResources().getString(R.string.theta_error_shortage_by_android), null); } }); return; } String root = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/"; File dir = new File(root); if (!dir.exists()) { dir.mkdir(); } Date date = new Date(); SimpleDateFormat fileDate = new SimpleDateFormat("yyyyMMdd_HHmmss"); final String fileName = "theta_vr_screenshot_" + fileDate.format(date) + ".jpg"; final String filePath = root + fileName; try { saveFile(filePath, mSphereView.takeSnapshot()); if (BuildConfig.DEBUG) { mLogger.severe("absolute path:" + filePath); } ContentValues values = new ContentValues(); ContentResolver contentResolver = getActivity().getContentResolver(); values.put(MediaStore.Images.Media.TITLE, fileName); values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName); values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); values.put(MediaStore.Images.Media.DATA, filePath); contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { ThetaDialogFragment.showAlert(getActivity(), getResources().getString(R.string.theta_ssid_prefix), getResources().getString(R.string.theta_save_screenshot), null); } }); } } catch (IOException e) { if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { failSaveDialog(); } }); } } finally { if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { if (mProgress != null) { mProgress.dismiss(); } } }); } } } @Override public void onFail() { Activity activity = getActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { if (mProgress != null) { mProgress.dismiss(); } failSaveDialog(); } }); } } }); }