List of usage examples for android.content ContentResolver query
public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder)
From source file:com.android.contacts.common.model.ContactLoader.java
private Contact loadContactEntity(ContentResolver resolver, Uri contactUri) { Uri entityUri = Uri.withAppendedPath(contactUri, Contacts.Entity.CONTENT_DIRECTORY); Cursor cursor = resolver.query(entityUri, ContactQuery.COLUMNS, null, null, Contacts.Entity.RAW_CONTACT_ID); if (cursor == null) { Log.e(TAG, "No cursor returned in loadContactEntity"); return Contact.forNotFound(mRequestedUri); }//from w w w. ja va 2s.co m try { if (!cursor.moveToFirst()) { cursor.close(); return Contact.forNotFound(mRequestedUri); } // Create the loaded contact starting with the header data. Contact contact = loadContactHeaderData(cursor, contactUri); // Fill in the raw contacts, which is wrapped in an Entity and any // status data. Initially, result has empty entities and statuses. long currentRawContactId = -1; RawContact rawContact = null; ImmutableList.Builder<RawContact> rawContactsBuilder = new ImmutableList.Builder<RawContact>(); ImmutableMap.Builder<Long, DataStatus> statusesBuilder = new ImmutableMap.Builder<Long, DataStatus>(); do { long rawContactId = cursor.getLong(ContactQuery.RAW_CONTACT_ID); if (rawContactId != currentRawContactId) { // First time to see this raw contact id, so create a new entity, and // add it to the result's entities. currentRawContactId = rawContactId; rawContact = new RawContact(loadRawContactValues(cursor)); rawContactsBuilder.add(rawContact); } if (!cursor.isNull(ContactQuery.DATA_ID)) { ContentValues data = loadDataValues(cursor); rawContact.addDataItemValues(data); if (!cursor.isNull(ContactQuery.PRESENCE) || !cursor.isNull(ContactQuery.STATUS)) { final DataStatus status = new DataStatus(cursor); final long dataId = cursor.getLong(ContactQuery.DATA_ID); statusesBuilder.put(dataId, status); } } } while (cursor.moveToNext()); contact.setRawContacts(rawContactsBuilder.build()); contact.setStatuses(statusesBuilder.build()); return contact; } finally { cursor.close(); } }
From source file:com.charabia.SmsViewActivity.java
@Override public void onActivityResult(int reqCode, int resultCode, Intent data) { super.onActivityResult(reqCode, resultCode, data); switch (reqCode) { case SMS_KEY_CONTACT: if (resultCode == RESULT_OK) { Uri uri = data.getData();//from ww w .j a v a2 s . com ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(uri, new String[] { Contacts.LOOKUP_KEY }, null, null, null); String lookup = null; if (cursor.moveToFirst()) { lookup = cursor.getString(0); } cursor.close(); if (lookup == null) { Toast.makeText(this, R.string.unexpected_error, Toast.LENGTH_LONG).show(); return; } cursor = cr.query(Data.CONTENT_URI, new String[] { Phone.NUMBER }, Data.MIMETYPE + "=? AND " + Data.LOOKUP_KEY + "=?", new String[] { Phone.CONTENT_ITEM_TYPE, lookup }, null); ArrayList<String> options = new ArrayList<String>(); while (cursor.moveToNext()) { options.add(cursor.getString(0)); } cursor.close(); final String[] phoneList = options.toArray(new String[0]); Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.send_invit_on_phone); builder.setItems(phoneList, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { keypair = tools.loadKeyPair(); RSAPublicKey pubKey = (RSAPublicKey) keypair.getPublic(); byte[] encoded = pubKey.getModulus().toByteArray(); byte[] data = new byte[3 + encoded.length]; data[0] = Tools.MAGIC[0]; data[1] = Tools.MAGIC[1]; data[2] = Tools.PUBLIC_KEY_TYPE; System.arraycopy(encoded, 0, data, 3, encoded.length); tools.sendData(phoneList[i], Tools.INVITATION, "", data); } }); builder.create().show(); } else { Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show(); } break; case IntentIntegrator.REQUEST_CODE: if (resultCode == RESULT_OK) { try { String contents = data.getStringExtra("SCAN_RESULT"); @SuppressWarnings("unused") String format = data.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan // TODO: add more tests control String[] infos = contents.split("\n"); Cipher rsaCipher = Cipher.getInstance(Tools.RSA_CIPHER_ALGO); if (mode == MODE_ESCLAVE) { // Save key and show crypted key on QRCode key = tools.generateKeyAES().getEncoded(); KeyFactory keyFact = KeyFactory.getInstance("RSA"); PublicKey pubkey = keyFact.generatePublic( new RSAPublicKeySpec(new BigInteger(infos[1]), new BigInteger(infos[2]))); rsaCipher.init(Cipher.ENCRYPT_MODE, pubkey); int blockSize = rsaCipher.getBlockSize(); int nbBlock = key.length / blockSize; int reste = key.length % blockSize; byte[] cryptedKey = new byte[(nbBlock + 1) * rsaCipher.getOutputSize(blockSize)]; int offset = 0; for (int i = 0; i < nbBlock; i++) { offset += rsaCipher.doFinal(key, i * blockSize, blockSize, cryptedKey, offset); } rsaCipher.doFinal(key, nbBlock * blockSize, reste, cryptedKey, offset); IntentIntegrator.shareText(SmsViewActivity.this, prefPhoneNumber + "\n" + Base64.encodeToString(cryptedKey, Base64.NO_WRAP)); } else { // We have read crypted key, so decode it rsaCipher.init(Cipher.DECRYPT_MODE, keypair.getPrivate()); byte[] cryptedData = Base64.decode(infos[1], Base64.NO_WRAP); int blockSize = rsaCipher.getBlockSize(); int nbBlock = cryptedData.length / blockSize; int offset = 0; byte[] tempKey = new byte[(nbBlock + 1) * blockSize]; for (int i = 0; i < nbBlock; i++) { offset += rsaCipher.doFinal(cryptedData, i * blockSize, blockSize, tempKey, offset); } key = new byte[offset]; System.arraycopy(tempKey, 0, key, 0, offset); } phoneNumber = infos[0]; // store the key // TODO dialog to confirm add contact in mode SLAVE try { new Tools(this).updateOrCreateContactKey(phoneNumber, key); } catch (NoContactException e) { e.printStackTrace(); // propose to add contact Intent newIntent = new Intent(Intents.SHOW_OR_CREATE_CONTACT); newIntent.setData(Uri.fromParts("tel", phoneNumber, null)); startActivityForResult(newIntent, ADD_CONTACT); return; } Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG) .show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show(); } } else { // TODO: string Toast.makeText(this, R.string.fail_reading_tag, Toast.LENGTH_LONG).show(); } break; case ADD_CONTACT: try { tools.updateOrCreateContactKey(phoneNumber, key); Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG) .show(); } catch (NoContactException e) { e.printStackTrace(); Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show(); } break; } }
From source file:com.bt.download.android.gui.Librarian.java
private Set<Integer> getSharedFiles(byte fileType) { TreeSet<Integer> result = new TreeSet<Integer>(); List<Integer> delete = new ArrayList<Integer>(); Cursor c = null;/*from ww w . ja v a 2s .co m*/ try { ContentResolver cr = context.getContentResolver(); String[] columns = new String[] { SharingColumns.FILE_ID, SharingColumns._ID }; c = cr.query(Sharing.Media.CONTENT_URI, columns, SharingColumns.SHARED + "=1 AND " + SharingColumns.FILE_TYPE + "=?", new String[] { String.valueOf(fileType) }, null); if (c == null || !c.moveToFirst()) { return result; } int fileIdCol = c.getColumnIndex(SharingColumns.FILE_ID); int sharingIdCol = c.getColumnIndex(SharingColumns._ID); Pair<List<Integer>, List<String>> pair = getAllFiles(fileType); List<Integer> files = pair.first; List<String> paths = pair.second; do { int fileId = c.getInt(fileIdCol); int sharingId = c.getInt(sharingIdCol); int index = Collections.binarySearch(files, fileId); try { if (index >= 0) { File f = new File(paths.get(index)); if (f.exists() && f.isFile()) { result.add(fileId); } else { delete.add(sharingId); } } else { delete.add(sharingId); } } catch (Throwable e) { Log.e(TAG, "Error checking fileId: " + fileId + ", fileType: " + fileId); } } while (c.moveToNext()); } catch (Throwable e) { Log.e(TAG, "General failure getting shared/unshared files ids", e); } finally { if (c != null) { c.close(); } if (delete.size() > 0) { deleteSharedStates(delete); } } return result; }
From source file:com.android.providers.downloads.DownloadService.java
/** * Update {@link #mDownloads} to match {@link DownloadProvider} state. * Depending on current download state it may enqueue {@link DownloadThread} * instances, request {@link DownloadScanner} scans, update user-visible * notifications, and/or schedule future actions with {@link AlarmManager}. * <p>/*from w w w . j a v a2s.com*/ * Should only be called from {@link #mUpdateThread} as after being * requested through {@link #enqueueUpdate()}. * * @return If there are active tasks being processed, as of the database * snapshot taken in this update. */ private boolean updateLocked() { final long now = mSystemFacade.currentTimeMillis(); boolean isActive = false; long nextActionMillis = Long.MAX_VALUE; final Set<Long> staleIds = Sets.newHashSet(mDownloads.keySet()); final ContentResolver resolver = getContentResolver(); Cursor cursor = null; try { cursor = resolver.query(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, null, null, null, null); final DownloadInfo.Reader reader = new DownloadInfo.Reader(resolver, cursor); final int idColumn = cursor.getColumnIndexOrThrow(Downloads.Impl._ID); while (cursor.moveToNext()) { final long id = cursor.getLong(idColumn); long currentDownloadNextActionMillis = Long.MAX_VALUE; DownloadInfo info = mDownloads.get(id); if (info != null) { updateDownload(reader, info, now); } else { // Check xunlei engine status when create a new task info = insertDownloadLocked(reader, now); } if (info.mDeleted) { // Delete download if requested, but only after cleaning up if (!TextUtils.isEmpty(info.mMediaProviderUri)) { resolver.delete(Uri.parse(info.mMediaProviderUri), null, null); } // if download has been completed, delete xxx, else delete xxx.midownload if (info.mStatus == Downloads.Impl.STATUS_SUCCESS) { if (info.mFileName != null) { deleteFileIfExists(info.mFileName); } } else { if (info.mFileName != null) { deleteFileIfExists(info.mFileName + Helpers.sDownloadingExtension); } } resolver.delete(info.getAllDownloadsUri(), null, null); } else { staleIds.remove(id); // Kick off download task if ready String pkg = TextUtils.isEmpty(info.mPackage) ? sUnknownPackage : info.mPackage; final boolean activeDownload = info.startDownloadIfReady(MyExecutor.getExecutorInstance(pkg)); // Kick off media scan if completed final boolean activeScan = info.startScanIfReady(mScanner); // get current download task's next action millis currentDownloadNextActionMillis = info.nextActionMillis(now); XLConfig.LOGD("Download " + info.mId + ": activeDownload=" + activeDownload + ", activeScan=" + activeScan); isActive |= activeDownload; isActive |= activeScan; // if equals 0, keep download service on. isActive |= (currentDownloadNextActionMillis == 0); } // Keep track of nearest next action nextActionMillis = Math.min(currentDownloadNextActionMillis, nextActionMillis); } } catch (SQLiteDiskIOException e) { XLConfig.LOGD("error when updateLocked: ", e); } catch (Exception e) { XLConfig.LOGD("error when updateLocked: ", e); } finally { if (cursor != null) { cursor.close(); } } // Clean up stale downloads that disappeared for (Long id : staleIds) { deleteDownloadLocked(id); } // Update notifications visible to user mNotifier.updateWith(mDownloads.values()); // Set alarm when next action is in future. It's okay if the service // continues to run in meantime, since it will kick off an update pass. if (nextActionMillis > 0 && nextActionMillis < Long.MAX_VALUE) { XLConfig.LOGD("scheduling start in " + nextActionMillis + "ms"); final Intent intent = new Intent(Constants.ACTION_RETRY); intent.setClass(this, DownloadReceiver.class); mAlarmManager.set(AlarmManager.RTC_WAKEUP, now + nextActionMillis, PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)); } return isActive; }
From source file:com.undatech.opaque.RemoteCanvasActivity.java
/** * Launches a remote desktop session using a .vv file. * @param i//from w ww.j a v a 2 s . com * @return the vv file name or NULL if no file was discovered. */ private String startSessionFromVvFile(Intent i) { final Uri data = i.getData(); String vvFileName = null; android.util.Log.d(TAG, "got intent: " + i.toString()); if (data != null) { android.util.Log.d(TAG, "got data: " + data.toString()); if (data.toString().startsWith("http")) { android.util.Log.d(TAG, "Intent is with http scheme."); final String tempVvFile = getFilesDir() + "/tempfile.vv"; vvFileName = tempVvFile; // Spin up a thread to grab the file over the network. Thread t = new Thread() { @Override public void run() { try { URL url = new URL(data.toString()); File file = new File(tempVvFile); URLConnection ucon = url.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(3000); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } FileOutputStream fos = new FileOutputStream(file); fos.write(baf.toByteArray()); fos.close(); synchronized (RemoteCanvasActivity.this) { RemoteCanvasActivity.this.notify(); } } catch (Exception e) { } } }; t.start(); synchronized (this) { try { this.wait(5000); } catch (InterruptedException e) { vvFileName = null; e.printStackTrace(); } } } else if (data.toString().startsWith("file")) { android.util.Log.d(TAG, "Intent is with file scheme."); vvFileName = data.getPath(); } else if (data.toString().startsWith("content")) { android.util.Log.d(TAG, "Intent is with content scheme."); String[] projection = { MediaStore.MediaColumns.DATA }; ContentResolver resolver = getApplicationContext().getContentResolver(); Cursor cursor = resolver.query(data, projection, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { vvFileName = cursor.getString(0); } cursor.close(); } } File f = new File(vvFileName); android.util.Log.d(TAG, "got filename: " + vvFileName); if (f.exists()) { android.util.Log.d(TAG, "Initializing session from vv file: " + vvFileName); connection = new ConnectionSettings("defaultSettings"); connection.loadFromSharedPreferences(getApplicationContext()); } else { vvFileName = null; // Quit with an error if the file does not exist. MessageDialogs.displayMessageAndFinish(this, R.string.vv_file_not_found, R.string.error_dialog_title); } } return vvFileName; }
From source file:com.bt.download.android.gui.Librarian.java
/** * Returns a list of Files./*from w ww .j av a 2 s . co m*/ * * @param offset * - from where (starting at 0) * @param pageSize * - how many results * @param fetcher * - An implementation of TableFetcher * @param sharedOnly * - if true, retrieves only the fine grained shared files. * * @return List<FileDescriptor> */ private List<FileDescriptor> getFiles(int offset, int pageSize, TableFetcher fetcher, String where, String[] whereArgs, boolean sharedOnly) { List<FileDescriptor> result = new ArrayList<FileDescriptor>(); Cursor c = null; Set<Integer> sharedIds = getSharedFiles(fetcher.getFileType()); try { ContentResolver cr = context.getContentResolver(); String[] columns = fetcher.getColumns(); String sort = fetcher.getSortByExpression(); c = cr.query(fetcher.getContentUri(), columns, where, whereArgs, sort); if (c == null || !c.moveToPosition(offset)) { return result; } fetcher.prepare(c); int count = 1; do { FileDescriptor fd = fetcher.fetch(c); fd.shared = sharedIds.contains(fd.id); if (sharedOnly && !fd.shared) { continue; } result.add(fd); } while (c.moveToNext() && count++ < pageSize); } catch (Throwable e) { Log.e(TAG, "General failure getting files", e); } finally { if (c != null) { c.close(); } } return result; }
From source file:com.ptts.sync.SyncAdapter.java
/** * Read JSON from an input stream, storing it into the content provider. * * <p>This is where incoming data is persisted, committing the results of a sync. In order to * minimize (expensive) disk operations, we compare incoming data with what's already in our * database, and compute a merge. Only changes (insert/update/delete) will result in a database * write.//ww w .jav a 2 s .c o m * * <p>As an additional optimization, we use a batch operation to perform all database writes at * once. * * <p>Merge strategy: * 1. Get cursor to all items in feed<br/> * 2. For each item, check if it's in the incoming data.<br/> * a. YES: Remove from "incoming" list. Check if data has mutated, if so, perform * database UPDATE.<br/> * b. NO: Schedule DELETE from database.<br/> * (At this point, incoming database only contains missing items.)<br/> * 3. For any items remaining in incoming list, ADD to database. */ public void updateLocalFeedData(final InputStream stream, final SyncResult syncResult) throws IOException, JSONException, RemoteException, OperationApplicationException, ParseException { final FeedParserJson feedParser = new FeedParserJson(); final ContentResolver contentResolver = getContext().getContentResolver(); Log.i(TAG, "Parsing stream as Json feed"); final List<FeedParserJson.Entry> entries = feedParser.parse(stream); Log.i(TAG, "Parsing complete. Found " + entries.size() + " entries"); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Build hash table of incoming entries HashMap<String, FeedParserJson.Entry> entryMap = new HashMap<String, FeedParserJson.Entry>(); for (FeedParserJson.Entry e : entries) { entryMap.put(e.id, e); } // Get list of all items Log.i(TAG, "Fetching local entries for merge"); Uri uri = FeedContract.Entry.CONTENT_URI; // Get all entries Cursor c = contentResolver.query(uri, PROJECTION, null, null, null); assert c != null; Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution..."); // Find stale data int id; String entryId; String name; String start; String end; String stops; while (c.moveToNext()) { syncResult.stats.numEntries++; id = c.getInt(COLUMN_ID); entryId = c.getString(COLUMN_ENTRY_ID); name = c.getString(COLUMN_NAME); start = c.getString(COLUMN_START); end = c.getString(COLUMN_END); stops = c.getString(COLUMN_STOPS); Log.i("STOPS FROM PROJECTION", stops); FeedParserJson.Entry match = entryMap.get(entryId); if (match != null) { // Entry exists. Remove from entry map to prevent insert later. entryMap.remove(entryId); // Check to see if the entry needs to be updated Uri existingUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)) .build(); if ((match.name != null && !match.name.equals(name)) || (match.start != null && !match.start.equals(start)) || (match.stops != null && !match.stops.equals(stops)) || (match.end != end)) { Log.i("STOPS FROM HASHMAP", match.stops); if (!match.stops.equals(stops)) { Log.i("COMPARING PROJECTION " + match.stops + " & HASHMAP " + stops, "The two aren't equal"); } else { Log.i("COMPARING PROJECTION & HASHMAP", "The two are equal"); } // Update existing record Log.i(TAG, "Scheduling update: " + existingUri); batch.add(ContentProviderOperation.newUpdate(existingUri) .withValue(FeedContract.Entry.COLUMN_NAME_ENTRY_ID, entryId) .withValue(FeedContract.Entry.COLUMN_NAME_NAME, name) .withValue(FeedContract.Entry.COLUMN_NAME_START, start) .withValue(FeedContract.Entry.COLUMN_NAME_END, end) .withValue(FeedContract.Entry.COLUMN_NAME_STOPS, stops).build()); syncResult.stats.numUpdates++; } else { Log.i(TAG, "No action: " + existingUri); } } else { // Entry doesn't exist. Remove it from the database. Uri deleteUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)).build(); Log.i(TAG, "Scheduling delete: " + deleteUri); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); syncResult.stats.numDeletes++; } } c.close(); // Add new items for (FeedParserJson.Entry e : entryMap.values()) { Log.i(TAG, "Scheduling insert: entry_id=" + e.id); batch.add(ContentProviderOperation.newInsert(FeedContract.Entry.CONTENT_URI) .withValue(FeedContract.Entry.COLUMN_NAME_ENTRY_ID, e.id) .withValue(FeedContract.Entry.COLUMN_NAME_NAME, e.name) .withValue(FeedContract.Entry.COLUMN_NAME_START, e.start) .withValue(FeedContract.Entry.COLUMN_NAME_END, e.end) .withValue(FeedContract.Entry.COLUMN_NAME_STOPS, e.stops).build()); syncResult.stats.numInserts++; } Log.i(TAG, "Merge solution ready. Applying batch update"); mContentResolver.applyBatch(FeedContract.CONTENT_AUTHORITY, batch); mContentResolver.notifyChange(FeedContract.Entry.CONTENT_URI, // URI where data was modified null, // No local observer false); // IMPORTANT: Do not sync to network // This sample doesn't support uploads, but if *your* code does, make sure you set // syncToNetwork=false in the line above to prevent duplicate syncs. }
From source file:com.ichi2.anki.tests.ContentProviderTest.java
/** * Check that updating the flds column works as expected *//* w ww . j a v a2 s . co m*/ public void testUpdateNoteFields() { final ContentResolver cr = getContext().getContentResolver(); ContentValues cv = new ContentValues(); // Change the fields so that the first field is now "newTestValue" String[] dummyFields2 = mDummyFields.clone(); dummyFields2[0] = TEST_FIELD_VALUE; for (Uri uri : mCreatedNotes) { // Update the flds cv.put(FlashCardsContract.Note.FLDS, Utils.joinFields(dummyFields2)); cr.update(uri, cv, null, null); // Query the table again Cursor noteCursor = cr.query(uri, FlashCardsContract.Note.DEFAULT_PROJECTION, null, null, null); try { assertNotNull("Check that there is a valid cursor for detail data after update", noteCursor); assertEquals("Check that there is one and only one entry after update", 1, noteCursor.getCount()); assertTrue("Move to first item in cursor", noteCursor.moveToFirst()); String[] newFlds = Utils .splitFields(noteCursor.getString(noteCursor.getColumnIndex(FlashCardsContract.Note.FLDS))); assertTrue("Check that the flds have been updated correctly", Arrays.equals(newFlds, dummyFields2)); } finally { noteCursor.close(); } } }
From source file:com.bt.download.android.gui.Librarian.java
private void syncMediaStore(byte fileType, Set<File> ignorableFiles) { TableFetcher fetcher = TableFetchers.getFetcher(fileType); Cursor c = null;/*from www . j ava 2 s .co m*/ try { ContentResolver cr = context.getContentResolver(); String where = MediaColumns.DATA + " LIKE ?"; String[] whereArgs = new String[] { SystemPaths.getAppStorage().getAbsolutePath() + "%" }; c = cr.query(fetcher.getContentUri(), new String[] { MediaColumns._ID, MediaColumns.DATA }, where, whereArgs, null); if (c == null) { return; } int idCol = c.getColumnIndex(MediaColumns._ID); int pathCol = c.getColumnIndex(MediaColumns.DATA); List<Integer> ids = new ArrayList<Integer>(); while (c.moveToNext()) { int id = Integer.valueOf(c.getString(idCol)); String path = c.getString(pathCol); if (ignorableFiles.contains(new File(path))) { ids.add(id); } } cr.delete(fetcher.getContentUri(), MediaColumns._ID + " IN " + StringUtils.buildSet(ids), null); } catch (Throwable e) { Log.e(TAG, "General failure during sync of MediaStore", e); } finally { if (c != null) { c.close(); } } }
From source file:com.andrew.apollo.utils.MusicUtils.java
/** * @param context The {@link Context} to use * @param id The song ID.// w ww .j a v a 2s . co m */ public static void setRingtone(final Context context, final long id) { final ContentResolver resolver = context.getContentResolver(); final Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id); try { final ContentValues values = new ContentValues(2); values.put(AudioColumns.IS_RINGTONE, "1"); values.put(AudioColumns.IS_ALARM, "1"); resolver.update(uri, values, null, null); } catch (final UnsupportedOperationException ignored) { return; } final String[] projection = new String[] { BaseColumns._ID, MediaColumns.DATA, MediaColumns.TITLE }; final String selection = BaseColumns._ID + "=" + id; Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection, null, null); try { if (cursor != null && cursor.getCount() == 1) { cursor.moveToFirst(); RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, uri); final String message = context.getString(R.string.set_as_ringtone, cursor.getString(2)); AppMsg.makeText(context, message, AppMsg.STYLE_CONFIRM).show(); } } catch (Throwable ignored) { UIUtils.showLongMessage(context, R.string.ringtone_not_set); } finally { if (cursor != null) { cursor.close(); } } }