List of usage examples for android.content ContentValues ContentValues
private ContentValues(Parcel in)
From source file:Main.java
private static Uri exportToGallery(Context context, String filename) { // Save the name and description of a video in a ContentValues map. final ContentValues values = new ContentValues(2); values.put(MediaStore.Video.Media.MIME_TYPE, "image/jpeg"); values.put(MediaStore.Video.Media.DATA, filename); // Add a new record (identified by uri) final Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); return uri;//from w w w . j av a 2 s . c o m }
From source file:Main.java
/** * Add an entry to the database//www .j av a 2 s . c om * * @param db * pointer to database * @param recordLine * String with a record * format: yy,mm,dd,hh:mm,light,solar,consumption * e.g.: "15,08,13,13:54,35000,613.456,-120.22" */ public static void addDay(SQLiteDatabase db, String recordLine) { /* Parse the string into its single values */ String[] valuesPerLine = recordLine.split(","); if (valuesPerLine.length == 1) { return; } /** String list with hour & minute values */ String[] hourSplit = valuesPerLine[3].split(":"); /** ContentValues to hold the measured and calculated values to be added to the database */ ContentValues values = new ContentValues(14); values.put("year", Integer.parseInt(valuesPerLine[0])); values.put("month", Integer.parseInt(valuesPerLine[1])); values.put("day", Integer.parseInt(valuesPerLine[2])); values.put("hour", Integer.parseInt(hourSplit[0])); values.put("minute", Integer.parseInt(hourSplit[1])); values.put("solar", Double.parseDouble(valuesPerLine[5])); values.put("cons", Double.parseDouble(valuesPerLine[6])); values.put("light", Long.parseLong(valuesPerLine[4])); db.insert(TABLE_NAME, null, values); }
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) *//*ww w .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. * //from w ww . j a v a2 s.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:Main.java
/** * @param context The {@link Context} to use. * @param name The name of the new playlist. * @return A new playlist ID./*from ww w. j av a2 s. co m*/ */ public static final long createPlaylist(final Context context, final String name) { if (name != null && name.length() > 0) { final ContentResolver resolver = context.getContentResolver(); final String[] projection = new String[] { PlaylistsColumns.NAME }; final String selection = PlaylistsColumns.NAME + " = '" + name + "'"; Cursor cursor = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection, selection, null, null); if (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); return Long.parseLong(uri.getLastPathSegment()); } if (cursor != null) { cursor.close(); cursor = null; } return -1; } return -1; }
From source file:com.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java
/** * Removes all data from themovies, thevideos, and thereviews tables. Does not remove data * flagged favorite but the columns istoprated, and ispopular will be set to false, "0". * @param context//from w w w. j av a 2 s. c om */ public static void deletePopularAndTopRated(Context context) { ContentResolver contentResolver = context.getContentResolver(); ContentValues removePopAndTop = new ContentValues(2); removePopAndTop.put(TMDbContract.Movies.IS_POPULAR, "0"); removePopAndTop.put(TMDbContract.Movies.IS_TOP_RATED, "0"); contentResolver.update(TMDbContract.Movies.URI, removePopAndTop, TMDbContract.Movies.IS_FAVORITE + " = ?", new String[] { "1" }); contentResolver.delete(TMDbContract.Movies.URI, TMDbContract.Movies.IS_POPULAR + " = ? OR " + TMDbContract.Movies.IS_TOP_RATED + " = ?", new String[] { "1", "1" }); Cursor favoriteMovieIds = getFavoriteIds(context); int numberOfIds = favoriteMovieIds.getCount(); String[] movieIds = new String[numberOfIds]; String whereClauseVideos = ""; String whereClauseReviews = ""; for (int i = 0; i < numberOfIds; i++) { favoriteMovieIds.moveToNext(); movieIds[i] = Integer.toString( favoriteMovieIds.getInt(favoriteMovieIds.getColumnIndex(TMDbContract.Movies.MOVIE_ID))); if (i == numberOfIds - 1) { whereClauseVideos += TMDbContract.Videos.MOVIE_IDS + " != ? "; whereClauseReviews += TMDbContract.Videos.MOVIE_IDS + " != ? "; } else { whereClauseVideos += TMDbContract.Videos.MOVIE_IDS + " != ? OR "; whereClauseReviews += TMDbContract.Reviews.MOVIE_IDS + " != ? OR "; } } contentResolver.delete(TMDbContract.Videos.URI, whereClauseVideos, movieIds); contentResolver.delete(TMDbContract.Reviews.URI, whereClauseReviews, movieIds); }
From source file:at.bitfire.davdroid.resource.LocalGroup.java
@Override public void clearDirty(String eTag) throws ContactsStorageException { assertID();// w ww . j a v a 2 s . com ContentValues values = new ContentValues(2); values.put(Groups.DIRTY, 0); values.put(COLUMN_ETAG, this.eTag = eTag); update(values); // update cached group memberships BatchOperation batch = new BatchOperation(addressBook.provider); // delete cached group memberships batch.enqueue(new BatchOperation.Operation(ContentProviderOperation .newDelete(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI)) .withSelection(CachedGroupMembership.MIMETYPE + "=? AND " + CachedGroupMembership.GROUP_ID + "=?", new String[] { CachedGroupMembership.CONTENT_ITEM_TYPE, String.valueOf(id) }))); // insert updated cached group memberships for (long member : getMembers()) batch.enqueue(new BatchOperation.Operation(ContentProviderOperation .newInsert(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI)) .withValue(CachedGroupMembership.MIMETYPE, CachedGroupMembership.CONTENT_ITEM_TYPE) .withValue(CachedGroupMembership.RAW_CONTACT_ID, member) .withValue(CachedGroupMembership.GROUP_ID, id).withYieldAllowed(true))); batch.commit(); }
From source file:com.android.exchange.adapter.Search.java
public static int searchMessages(Context context, long accountId, SearchParams searchParams, long destMailboxId) { // Sanity check for arguments final int offset = searchParams.mOffset; final int limit = searchParams.mLimit; final String filter = searchParams.mFilter; if (limit < 0 || limit > MAX_SEARCH_RESULTS || offset < 0) return 0; // TODO Should this be checked in UI? Are there guidelines for minimums? if (filter == null || filter.length() < MIN_QUERY_LENGTH) return 0; int res = 0;//from w ww . ja va 2 s . co m final Account account = Account.restoreAccountWithId(context, accountId); if (account == null) return res; final EasSyncService svc = EasSyncService.setupServiceForAccount(context, account); if (svc == null) return res; final Mailbox searchMailbox = Mailbox.restoreMailboxWithId(context, destMailboxId); // Sanity check; account might have been deleted? if (searchMailbox == null) return res; final ContentValues statusValues = new ContentValues(2); try { // Set the status of this mailbox to indicate query statusValues.put(Mailbox.UI_SYNC_STATUS, UIProvider.SyncStatus.LIVE_QUERY); searchMailbox.update(context, statusValues); svc.mMailbox = searchMailbox; svc.mAccount = account; final Serializer s = new Serializer(); s.start(Tags.SEARCH_SEARCH).start(Tags.SEARCH_STORE); s.data(Tags.SEARCH_NAME, "Mailbox"); s.start(Tags.SEARCH_QUERY).start(Tags.SEARCH_AND); s.data(Tags.SYNC_CLASS, "Email"); // If this isn't an inbox search, then include the collection id final Mailbox inbox = Mailbox.restoreMailboxOfType(context, accountId, Mailbox.TYPE_INBOX); if (inbox == null) return 0; if (searchParams.mMailboxId != inbox.mId) { s.data(Tags.SYNC_COLLECTION_ID, inbox.mServerId); } s.data(Tags.SEARCH_FREE_TEXT, filter); // Add the date window if appropriate if (searchParams.mStartDate != null) { s.start(Tags.SEARCH_GREATER_THAN); s.tag(Tags.EMAIL_DATE_RECEIVED); s.data(Tags.SEARCH_VALUE, Eas.DATE_FORMAT.format(searchParams.mStartDate)); s.end(); // SEARCH_GREATER_THAN } if (searchParams.mEndDate != null) { s.start(Tags.SEARCH_LESS_THAN); s.tag(Tags.EMAIL_DATE_RECEIVED); s.data(Tags.SEARCH_VALUE, Eas.DATE_FORMAT.format(searchParams.mEndDate)); s.end(); // SEARCH_LESS_THAN } s.end().end(); // SEARCH_AND, SEARCH_QUERY s.start(Tags.SEARCH_OPTIONS); if (offset == 0) { s.tag(Tags.SEARCH_REBUILD_RESULTS); } if (searchParams.mIncludeChildren) { s.tag(Tags.SEARCH_DEEP_TRAVERSAL); } // Range is sent in the form first-last (e.g. 0-9) s.data(Tags.SEARCH_RANGE, offset + "-" + (offset + limit - 1)); s.start(Tags.BASE_BODY_PREFERENCE); s.data(Tags.BASE_TYPE, Eas.BODY_PREFERENCE_HTML); s.data(Tags.BASE_TRUNCATION_SIZE, "20000"); s.end(); // BASE_BODY_PREFERENCE s.end().end().end().done(); // SEARCH_OPTIONS, SEARCH_STORE, SEARCH_SEARCH final EasResponse resp = svc.sendHttpClientPost("Search", s.toByteArray()); try { final int code = resp.getStatus(); if (code == HttpStatus.SC_OK) { final InputStream is = resp.getInputStream(); try { final SearchParser sp = new SearchParser(is, svc, filter); sp.parse(); res = sp.getTotalResults(); } finally { is.close(); } } else { svc.userLog("Search returned " + code); } } finally { resp.close(); } } catch (IOException e) { svc.userLog("Search exception " + e); } finally { // TODO: Handle error states // Set the status of this mailbox to indicate query over statusValues.put(Mailbox.SYNC_TIME, System.currentTimeMillis()); statusValues.put(Mailbox.UI_SYNC_STATUS, UIProvider.SyncStatus.NO_SYNC); searchMailbox.update(context, statusValues); } // Return the total count return res; }
From source file:com.manning.androidhacks.hack037.MainActivity.java
public void onLoop1Click(View v) { if (!canWriteInExternalStorage()) { Toast.makeText(this, "Can't write file", Toast.LENGTH_SHORT).show(); return;//from w w w .ja v a 2 s. c o m } Log.d("TAG", "LOOP1: " + LOOP1_PATH); MediaUtils.saveRaw(this, R.raw.loop1, LOOP1_PATH); ContentValues values = new ContentValues(5); values.put(Media.ARTIST, "Android"); values.put(Media.ALBUM, "60AH"); values.put(Media.TITLE, "hack043"); values.put(Media.MIME_TYPE, "audio/mp3"); values.put(Media.DATA, LOOP1_PATH); getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values); }
From source file:me.ziccard.secureit.async.AudioRecorderTask.java
@Override public void run() { MicrophoneTaskFactory.pauseSampling(); while (MicrophoneTaskFactory.isSampling()) { try {/*www . j a v a2 s . c o m*/ Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } recording = true; final MediaRecorder recorder = new MediaRecorder(); ContentValues values = new ContentValues(3); values.put(MediaStore.MediaColumns.TITLE, filename); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); String audioPath = Environment.getExternalStorageDirectory().getPath() + filename + ".m4a"; recorder.setOutputFile(audioPath); try { recorder.prepare(); } catch (Exception e) { e.printStackTrace(); return; } Log.i("AudioRecorderTask", "Start recording"); recorder.start(); try { Thread.sleep(prefs.getAudioLenght()); } catch (InterruptedException e) { e.printStackTrace(); } recorder.stop(); Log.i("AudioRecorderTask", "Stopped recording"); recorder.release(); recording = false; MicrophoneTaskFactory.restartSampling(); /* * Uploading the audio */ Log.i("AudioRecorderTask", "Trying to upload"); HttpClient httpclient = new DefaultHttpClient(); HttpPost request = new HttpPost(Remote.HOST + Remote.PHONES + "/" + phoneId + Remote.UPLOAD_AUDIO); Log.i("AudioRecorderTask", "URI: " + Remote.HOST + Remote.PHONES + "/" + phoneId + Remote.UPLOAD_AUDIO); /* * Getting the audio from the file system */ MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File audio = new File(audioPath); reqEntity.addPart("audio", new FileBody(audio, "audio/mp3")); request.setEntity(reqEntity); /* * Authentication token */ request.setHeader("access_token", accessToken); try { HttpResponse response = httpclient.execute(request); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } Log.i("AudioRecorderTask", "Response:\n" + builder.toString()); if (response.getStatusLine().getStatusCode() != 200) { Log.i("AudioRecorderTask", "Error uploading audio: " + audioPath); throw new HttpException(); } } catch (Exception e) { Log.e("DataUploaderTask", "Error uploading audio: " + audioPath); } }