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.dwdesign.tweetings.util.Utils.java
public static ParcelableStatus findStatusInDatabases(final Context context, final long account_id, final long status_id) { if (context == null) return null; final ContentResolver resolver = context.getContentResolver(); ParcelableStatus status = null;//from ww w .j a v a 2s .c o m final String where = Statuses.ACCOUNT_ID + " = " + account_id + " AND " + Statuses.STATUS_ID + " = " + status_id; for (final Uri uri : STATUSES_URIS) { final Cursor cur = resolver.query(uri, Statuses.COLUMNS, where, null, null); if (cur == null) { continue; } if (cur.getCount() > 0) { cur.moveToFirst(); status = new ParcelableStatus(cur, new StatusCursorIndices(cur)); } cur.close(); } return status; }
From source file:com.dwdesign.tweetings.util.Utils.java
public static ParcelableDirectMessage findDirectMessageInDatabases(final Context context, final long account_id, final long message_id) { if (context == null) return null; final ContentResolver resolver = context.getContentResolver(); ParcelableDirectMessage message = null; final String where = DirectMessages.ACCOUNT_ID + " = " + account_id + " AND " + DirectMessages.MESSAGE_ID + " = " + message_id; for (final Uri uri : DIRECT_MESSAGES_URIS) { final Cursor cur = resolver.query(uri, DirectMessages.COLUMNS, where, null, null); if (cur == null) { continue; }/* ww w. ja v a2 s . c o m*/ if (cur.getCount() > 0) { cur.moveToFirst(); message = new ParcelableDirectMessage(cur, new DirectMessageCursorIndices(cur)); } cur.close(); } return message; }
From source file:com.fat246.cybercar.services.MusicService.java
private int getmCardId() { final ContentResolver resolver = getContentResolver(); Cursor cursor = resolver.query(Uri.parse("content://media/external/fs_id"), null, null, null, null); int mCardId = -1; if (cursor != null && cursor.moveToFirst()) { Log.e("here", "comes"); mCardId = cursor.getInt(0);/* w w w. ja va2s . co m*/ cursor.close(); cursor = null; } return mCardId; }
From source file:com.andrew.apolloMod.service.ApolloService.java
private boolean makeAutoShuffleList() { ContentResolver res = getContentResolver(); Cursor c = null;// ww w . ja va 2 s . co m try { c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] { BaseColumns._ID }, AudioColumns.IS_MUSIC + "=1", null, null); if (c == null || c.getCount() == 0) { return false; } int len = c.getCount(); long[] list = new long[len]; for (int i = 0; i < len; i++) { c.moveToNext(); list[i] = c.getLong(0); } mAutoShuffleList = list; return true; } catch (RuntimeException ex) { } finally { if (c != null) { c.close(); } } return false; }
From source file:com.android.mms.ui.MessageUtils.java
/** M: * Return the current storage status./* www . j a v a2s . c om*/ */ public static String getStorageStatus(Context context) { /// M: we need count only final String[] PROJECTION = new String[] { BaseColumns._ID, Mms.MESSAGE_SIZE }; final ContentResolver cr = context.getContentResolver(); final Resources res = context.getResources(); Cursor cursor = null; StringBuilder buffer = new StringBuilder(); // Mms count cursor = cr.query(Mms.CONTENT_URI, PROJECTION, null, null, null); int mmsCount = 0; if (cursor != null) { mmsCount = cursor.getCount(); } buffer.append(res.getString(R.string.storage_dialog_mms, mmsCount)); buffer.append("\n"); //Mms size long size = 0; if (cursor != null) { if (cursor.moveToFirst()) { do { size += cursor.getInt(1); } while (cursor.moveToNext()); } cursor.close(); } buffer.append(res.getString(R.string.storage_dialog_mms_size) + getHumanReadableSize(size)); buffer.append("\n"); // Attachment size size = getAttachmentSize(context); Log.d(TAG, "mms attachment size = " + size); final String sizeTag = getHumanReadableSize(size); buffer.append(res.getString(R.string.storage_dialog_attachments) + sizeTag); buffer.append("\n"); // Sms count cursor = cr.query(Sms.CONTENT_URI, PROJECTION, null, null, null); int smsCount = 0; if (cursor != null) { smsCount = cursor.getCount(); cursor.close(); } buffer.append(res.getString(R.string.storage_dialog_sms, smsCount)); buffer.append("\n"); // Database size final long dbsize = getDatabaseSize(context); buffer.append(res.getString(R.string.storage_dialog_database) + getHumanReadableSize(dbsize)); buffer.append("\n"); // Available space final StatFs datafs = new StatFs(Environment.getDataDirectory().getAbsolutePath()); final long availableSpace = (long) datafs.getAvailableBlocks() * datafs.getBlockSize(); buffer.append( res.getString(R.string.storage_dialog_available_space) + getHumanReadableSize(availableSpace)); return buffer.toString(); }
From source file:com.andrew.apolloMod.service.ApolloService.java
/** * Method that query the media database for search a path an translate * to the internal media id//from w w w .j a v a 2s. c om * * @param path The path to search * @return long The id of the resource, or -1 if not found */ public long getIdFromPath(String path) { try { // Remove schema for search in the database // Otherwise the file will not found String data = path; if (data.startsWith("file://")) { data = data.substring(7); } ContentResolver resolver = getContentResolver(); String where = MediaColumns.DATA + "=?"; String selectionArgs[] = new String[] { data }; Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursorCols, where, selectionArgs, null); try { if (cursor == null || cursor.getCount() == 0) { return -1; } cursor.moveToNext(); return cursor.getLong(IDCOLIDX); } finally { try { if (cursor != null) cursor.close(); } catch (Exception ex) { } } } catch (UnsupportedOperationException ex) { } return -1; }
From source file:com.android.exchange.EasSyncService.java
private int parsePingResult(InputStream is, ContentResolver cr, HashMap<String, Integer> errorMap) throws IOException, StaleFolderListException, IllegalHeartbeatException { PingParser pp = new PingParser(is, this); if (pp.parse()) { // True indicates some mailboxes need syncing... // syncList has the serverId's of the mailboxes... mBindArguments[0] = Long.toString(mAccount.mId); mPingChangeList = pp.getSyncList(); for (String serverId : mPingChangeList) { mBindArguments[1] = serverId; Cursor c = cr.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, WHERE_ACCOUNT_KEY_AND_SERVER_ID, mBindArguments, null); try { if (c.moveToFirst()) { /**/*from w ww. j a va 2 s .c om*/ * Check the boxes reporting changes to see if there really were any... * We do this because bugs in various Exchange servers can put us into a * looping behavior by continually reporting changes in a mailbox, even when * there aren't any. * * This behavior is seemingly random, and therefore we must code defensively * by backing off of push behavior when it is detected. * * One known cause, on certain Exchange 2003 servers, is acknowledged by * Microsoft, and the server hotfix for this case can be found at * http://support.microsoft.com/kb/923282 */ // Check the status of the last sync String status = c.getString(Mailbox.CONTENT_SYNC_STATUS_COLUMN); int type = SyncManager.getStatusType(status); // This check should always be true... if (type == SyncManager.SYNC_PING) { int changeCount = SyncManager.getStatusChangeCount(status); if (changeCount > 0) { errorMap.remove(serverId); } else if (changeCount == 0) { // This means that a ping reported changes in error; we keep a count // of consecutive errors of this kind String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); Integer failures = errorMap.get(serverId); if (failures == null) { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, 1); } else if (failures > MAX_PING_FAILURES) { // We'll back off of push for this box pushFallback(c.getLong(Mailbox.CONTENT_ID_COLUMN)); continue; } else { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, failures + 1); } } } // If there were no problems with previous sync, we'll start another one SyncManager.startManualSync(c.getLong(Mailbox.CONTENT_ID_COLUMN), SyncManager.SYNC_PING, null); } } finally { c.close(); } } } return pp.getSyncStatus(); }
From source file:com.android.exchange.adapter.EmailSyncAdapter.java
@Override public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mContext.getContentResolver(); if (getSyncKey().equals("0")) { return false; }/*from w ww .j a va 2 s . c o m*/ // Never upsync from these folders if (mMailbox.mType == Mailbox.TYPE_DRAFTS || mMailbox.mType == Mailbox.TYPE_OUTBOX) { return false; } // This code is split out for unit testing purposes boolean firstCommand = sendDeletedItems(s, mDeletedIdList, true); if (!mFetchRequestList.isEmpty()) { // Add FETCH commands for messages that need a body (i.e. we didn't find it during // our earlier sync; this happens only in EAS 2.5 where the body couldn't be found // after parsing the message's MIME data) if (firstCommand) { s.start(Tags.SYNC_COMMANDS); firstCommand = false; } for (FetchRequest req : mFetchRequestList) { s.start(Tags.SYNC_FETCH).data(Tags.SYNC_SERVER_ID, req.serverId).end(); } } // Find our trash mailbox, since deletions will have been moved there... long trashMailboxId = Mailbox.findMailboxOfType(mContext, mMailbox.mAccountKey, Mailbox.TYPE_TRASH); // Do the same now for updated items Cursor c = cr.query(Message.UPDATED_CONTENT_URI, Message.LIST_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); // We keep track of the list of updated item id's as we did above with deleted items mUpdatedIdList.clear(); try { ContentValues cv = new ContentValues(); while (c.moveToNext()) { long id = c.getLong(Message.LIST_ID_COLUMN); // Say we've handled this update mUpdatedIdList.add(id); // We have the id of the changed item. But first, we have to find out its current // state, since the updated table saves the opriginal state Cursor currentCursor = cr.query(ContentUris.withAppendedId(Message.CONTENT_URI, id), UPDATES_PROJECTION, null, null, null); try { // If this item no longer exists (shouldn't be possible), just move along if (!currentCursor.moveToFirst()) { continue; } // Keep going if there's no serverId String serverId = currentCursor.getString(UPDATES_SERVER_ID_COLUMN); if (serverId == null) { continue; } boolean flagChange = false; boolean readChange = false; long mailbox = currentCursor.getLong(UPDATES_MAILBOX_KEY_COLUMN); // If the message is now in the trash folder, it has been deleted by the user if (mailbox == trashMailboxId) { if (firstCommand) { s.start(Tags.SYNC_COMMANDS); firstCommand = false; } // Send the command to delete this message s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end(); // Mark the message as moved (so the copy will be deleted if/when the server // version is synced) int flags = c.getInt(Message.LIST_FLAGS_COLUMN); cv.put(MessageColumns.FLAGS, flags | EasSyncService.MESSAGE_FLAG_MOVED_MESSAGE); cr.update(ContentUris.withAppendedId(Message.CONTENT_URI, id), cv, null, null); continue; } else if (mailbox != c.getLong(Message.LIST_MAILBOX_KEY_COLUMN)) { // The message has moved to another mailbox; add a request for this // Note: The Sync command doesn't handle moving messages, so we need // to handle this as a "request" (similar to meeting response and // attachment load) mService.addRequest(new MessageMoveRequest(id, mailbox)); // Regardless of other changes that might be made, we don't want to indicate // that this message has been updated until the move request has been // handled (without this, a crash between the flag upsync and the move // would cause the move to be lost) mUpdatedIdList.remove(id); } // We can only send flag changes to the server in 12.0 or later int flag = 0; if (mService.mProtocolVersionDouble >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) { flag = currentCursor.getInt(UPDATES_FLAG_COLUMN); if (flag != c.getInt(Message.LIST_FAVORITE_COLUMN)) { flagChange = true; } } int read = currentCursor.getInt(UPDATES_READ_COLUMN); if (read != c.getInt(Message.LIST_READ_COLUMN)) { readChange = true; } if (!flagChange && !readChange) { // In this case, we've got nothing to send to the server continue; } if (firstCommand) { s.start(Tags.SYNC_COMMANDS); firstCommand = false; } // Send the change to "read" and "favorite" (flagged) s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, c.getString(Message.LIST_SERVER_ID_COLUMN)) .start(Tags.SYNC_APPLICATION_DATA); if (readChange) { s.data(Tags.EMAIL_READ, Integer.toString(read)); } // "Flag" is a relatively complex concept in EAS 12.0 and above. It is not only // the boolean "favorite" that we think of in Gmail, but it also represents a // follow up action, which can include a subject, start and due dates, and even // recurrences. We don't support any of this as yet, but EAS 12.0 and higher // require that a flag contain a status, a type, and four date fields, two each // for start date and end (due) date. if (flagChange) { if (flag != 0) { // Status 2 = set flag s.start(Tags.EMAIL_FLAG).data(Tags.EMAIL_FLAG_STATUS, "2"); // "FollowUp" is the standard type s.data(Tags.EMAIL_FLAG_TYPE, "FollowUp"); long now = System.currentTimeMillis(); Calendar calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.setTimeInMillis(now); // Flags are required to have a start date and end date (duplicated) // First, we'll set the current date/time in GMT as the start time String utc = formatDateTime(calendar); s.data(Tags.TASK_START_DATE, utc).data(Tags.TASK_UTC_START_DATE, utc); // And then we'll use one week from today for completion date calendar.setTimeInMillis(now + 1 * WEEKS); utc = formatDateTime(calendar); s.data(Tags.TASK_DUE_DATE, utc).data(Tags.TASK_UTC_DUE_DATE, utc); s.end(); } else { s.tag(Tags.EMAIL_FLAG); } } s.end().end(); // SYNC_APPLICATION_DATA, SYNC_CHANGE } finally { currentCursor.close(); } } } finally { c.close(); } if (!firstCommand) { s.end(); // SYNC_COMMANDS } return false; }
From source file:br.com.viniciuscr.notification2android.mediaPlayer.MediaPlaybackService.java
/** * Opens the specified file and readies it for playback. * * @param path The full path of the file to be opened. *///from w ww.jav a 2s .co m public boolean open(String path) { synchronized (this) { if (path == null) { return false; } // if mCursor is null, try to associate path with a database cursor if (mCursor == null) { ContentResolver resolver = getContentResolver(); Uri uri; String where; String selectionArgs[]; if (path.startsWith("content://media/")) { uri = Uri.parse(path); where = null; selectionArgs = null; } else { uri = MediaStore.Audio.Media.getContentUriForPath(path); where = MediaStore.Audio.Media.DATA + "=?"; selectionArgs = new String[] { path }; } try { mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null); if (mCursor != null) { if (mCursor.getCount() == 0) { mCursor.close(); mCursor = null; } else { mCursor.moveToNext(); ensurePlayListCapacity(1); mPlayListLen = 1; mPlayList[0] = mCursor.getLong(IDCOLIDX); mPlayPos = 0; } } } catch (UnsupportedOperationException ex) { } } mFileToPlay = path; mPlayer.setDataSource(mFileToPlay); if (mPlayer.isInitialized()) { mOpenFailedCounter = 0; return true; } stop(true); return false; } }
From source file:com.akop.bach.parser.XboxLiveParser.java
private void parseMessages(XboxLiveAccount account) throws IOException, ParserException { long started = System.currentTimeMillis(); String token = getVToken(String.format(URL_VTOKEN_MESSAGES, mLocale)); String url = String.format(URL_JSON_MESSAGE_LIST, mLocale); List<NameValuePair> inputs = new ArrayList<NameValuePair>(3); addValue(inputs, "__RequestVerificationToken", token); String page = getResponse(url, inputs, true); JSONObject data = getXboxJsonObject(page); if (data == null) throw new ParserException(mContext, R.string.error_message_retrieval); JSONArray messages = data.optJSONArray("Messages"); if (App.getConfig().logToConsole()) started = displayTimeTaken("Message page fetch", started); long updated = started; boolean changed = false; String uid;/* w w w. ja v a 2s . co m*/ ContentResolver cr = mContext.getContentResolver(); Cursor c; ContentValues cv; List<ContentValues> newCvs = new ArrayList<ContentValues>(); final String[] columns = new String[] { Messages._ID, Messages.IS_READ }; for (int i = 0, n = messages.length(); i < n; i++) { JSONObject message = messages.optJSONObject(i); if (message == null || (uid = message.optString("Id")) == null) continue; int isRead = message.optBoolean("HasBeenRead") ? 1 : 0; c = cr.query(Messages.CONTENT_URI, columns, Messages.ACCOUNT_ID + "=" + account.getId() + " AND " + Messages.UID + "=" + uid, null, null); try { if (c != null && c.moveToFirst()) { String gamerpic = message.optString("GamerPic"); // Message already in system cv = new ContentValues(5); cv.put(Messages.IS_READ, isRead); cv.put(Messages.DELETE_MARKER, updated); cv.put(Messages.GAMERPIC, gamerpic); changed = true; cr.update(Messages.CONTENT_URI, cv, Messages._ID + "=" + c.getLong(0), null); } else { long sent = parseTicks(message.optString("SentTime")); String body = message.optString("Excerpt", ""); String sender = message.optString("From", ""); String gamerpic = message.optString("GamerPic"); int type = XboxLive.MESSAGE_TEXT; if (message.optBoolean("HasImage")) type = XboxLive.MESSAGE_OTHER; if (message.optBoolean("HasVoice")) type = XboxLive.MESSAGE_VOICE; // New message cv = new ContentValues(10); cv.put(Messages.ACCOUNT_ID, account.getId()); cv.put(Messages.SENDER, sender); cv.put(Messages.GAMERPIC, gamerpic); cv.put(Messages.UID, uid); cv.put(Messages.IS_READ, isRead); cv.put(Messages.IS_DIRTY, 1); cv.put(Messages.TYPE, type); cv.put(Messages.SENT, sent); cv.put(Messages.DELETE_MARKER, updated); cv.put(Messages.BODY, htmlDecode(body)); newCvs.add(cv); } } finally { if (c != null) c.close(); } } if (App.getConfig().logToConsole()) started = displayTimeTaken("Message list processing", started); if (newCvs.size() > 0) { changed = true; ContentValues[] cvs = new ContentValues[newCvs.size()]; newCvs.toArray(cvs); cr.bulkInsert(Messages.CONTENT_URI, cvs); if (App.getConfig().logToConsole()) displayTimeTaken("Message list insertion", started); } int deleted = cr.delete(Messages.CONTENT_URI, Messages.DELETE_MARKER + "!=" + updated + " AND " + Messages.ACCOUNT_ID + "=" + account.getId(), null); account.refresh(Preferences.get(mContext)); account.setLastMessageUpdate(System.currentTimeMillis()); account.save(Preferences.get(mContext)); if (changed || deleted > 0) cr.notifyChange(Messages.CONTENT_URI, null); }