Example usage for android.content ContentResolver query

List of usage examples for android.content ContentResolver query

Introduction

In this page you can find the example usage for android.content ContentResolver query.

Prototype

public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri, @Nullable String[] projection,
        @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) 

Source Link

Document

Query the given URI, returning a Cursor over the result set.

Usage

From source file:com.tct.email.NotificationController.java

/**
 * query the oubox's folder.//from   www.ja  v  a 2 s .c  o m
 * @param conentResolver
 * @param accountId
 * @return Folder
 */
private Folder queryUIFolder(ContentResolver conentResolver, long accountId) {
    Mailbox outbox = Mailbox.restoreMailboxOfType(mContext, accountId, Mailbox.TYPE_OUTBOX);
    if (outbox == null) {
        LogUtils.e(LOG_TAG, "null oubox in queryUIFolder,may account deleted,return");
        return null;
    }
    Uri folderUri = EmailProvider.uiUri("uifolder", outbox.mId);
    Cursor folderCursor = conentResolver.query(folderUri, UIProvider.FOLDERS_PROJECTION, null, null, null);
    Folder folder = null;
    if (folderCursor != null) {
        try {
            if (folderCursor.moveToFirst()) {
                folder = new Folder(folderCursor);
            } else {
                LogUtils.e(LOG_TAG, "Empty folder cursor for account ", "mail uri is", folderUri);
                return folder;
            }
        } finally {
            folderCursor.close();
        }
    }
    return folder;
}

From source file:com.securecomcode.text.contacts.ContactAccessor.java

/***
 * If the code below looks shitty to you, that's because it was taken
 * directly from the Android source, where shitty code is all you get.
 *///w  w w  .  j  av  a2 s . c om

public Cursor getCursorForRecipientFilter(CharSequence constraint, ContentResolver mContentResolver) {
    final String SORT_ORDER = Contacts.TIMES_CONTACTED + " DESC," + Contacts.DISPLAY_NAME + ","
            + Contacts.Data.IS_SUPER_PRIMARY + " DESC," + Phone.TYPE;

    final String[] PROJECTION_PHONE = { Phone._ID, // 0
            Phone.CONTACT_ID, // 1
            Phone.TYPE, // 2
            Phone.NUMBER, // 3
            Phone.LABEL, // 4
            Phone.DISPLAY_NAME, // 5
    };

    String phone = "";
    String cons = null;

    if (constraint != null) {
        cons = constraint.toString();

        if (RecipientsAdapter.usefulAsDigits(cons)) {
            phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons);
            if (phone.equals(cons) && !PhoneNumberUtils.isWellFormedSmsAddress(phone)) {
                phone = "";
            } else {
                phone = phone.trim();
            }
        }
    }
    Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(cons));
    String selection = String.format("%s=%s OR %s=%s OR %s=%s", Phone.TYPE, Phone.TYPE_MOBILE, Phone.TYPE,
            Phone.TYPE_WORK_MOBILE, Phone.TYPE, Phone.TYPE_MMS);

    Cursor phoneCursor = mContentResolver.query(uri, PROJECTION_PHONE, null, null, SORT_ORDER);

    if (phone.length() > 0) {
        ArrayList result = new ArrayList();
        result.add(Integer.valueOf(-1)); // ID
        result.add(Long.valueOf(-1)); // CONTACT_ID
        result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE
        result.add(phone); // NUMBER

        /*
        * The "\u00A0" keeps Phone.getDisplayLabel() from deciding
        * to display the default label ("Home") next to the transformation
        * of the letters into numbers.
        */
        result.add("\u00A0"); // LABEL
        result.add(cons); // NAME

        ArrayList<ArrayList> wrap = new ArrayList<ArrayList>();
        wrap.add(result);

        ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap);

        return new MergeCursor(new Cursor[] { translated, phoneCursor });
    } else {
        return phoneCursor;
    }
}

From source file:edu.mit.mobile.android.locast.data.MediaSync.java

/**
 * Scans the media database to see if the given item is currently there. If
 * it is, update the cast media to point to the local content: URI for it.
 *
 * @param context/* w w  w .ja  va2s.  c o  m*/
 * @param castMedia
 *            Local URI to the cast.
 * @param pubUri
 *            public URI to the media file.
 * @return local URI if it exists.
 * @throws SyncException
 */
public String checkForMediaEntry(Uri castMedia, Uri pubUri, String mimeType) throws SyncException {
    final ContentResolver cr = getContentResolver();

    String newLocUri = null;
    final File destfile = getFilePath(pubUri);

    if (mimeType == null) {
        throw new SyncException("missing MIME type");
    }

    String[] projection;
    String selection;
    Uri contentUri;

    if (mimeType.startsWith("image/")) {
        projection = new String[] { Images.Media._ID, Images.Media.DATA };
        selection = Images.Media.DATA + "=?";
        contentUri = Images.Media.EXTERNAL_CONTENT_URI;

    } else if (mimeType.startsWith("video/")) {
        projection = new String[] { Video.Media._ID, Video.Media.DATA };
        selection = Video.Media.DATA + "=?";
        contentUri = Video.Media.EXTERNAL_CONTENT_URI;

    } else {
        throw new SyncException("unknown MIME type: '" + mimeType + "'");
    }

    final String[] selectionArgs = { destfile.getAbsolutePath() };

    final Cursor mediaEntry = cr.query(contentUri, projection, selection, selectionArgs, null);
    try {
        if (mediaEntry.moveToFirst()) {
            newLocUri = ContentUris
                    .withAppendedId(contentUri, mediaEntry.getLong(mediaEntry.getColumnIndex(BaseColumns._ID)))
                    .toString();
        }
    } finally {
        mediaEntry.close();
    }

    if (newLocUri != null) {
        updateCastMediaLocalUri(castMedia, newLocUri, mimeType);
    } else {
        Log.e(TAG, "The media provider doesn't seem to know about " + destfile.getAbsolutePath()
                + " which is on the filesystem. Strange...");
    }
    return newLocUri;
}

From source file:com.akop.bach.parser.PsnUsParser.java

protected void parseFriendSummary(PsnAccount account, String friendOnlineId)
        throws ParserException, IOException {
    long updated = System.currentTimeMillis();
    long started = updated;

    GamerProfileInfo gpi = parseGamerProfile(account, friendOnlineId);

    ContentResolver cr = mContext.getContentResolver();
    Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION,
            Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?",
            new String[] { friendOnlineId }, null);

    long friendId = -1;

    try {//from  ww  w .  j av  a 2s .  co  m
        if (c != null && c.moveToFirst())
            friendId = c.getLong(0);
    } finally {
        if (c != null)
            c.close();
    }

    ContentValues cv = new ContentValues(15);

    cv.put(Friends.ONLINE_ID, gpi.OnlineId);
    cv.put(Friends.ICON_URL, gpi.AvatarUrl);
    cv.put(Friends.LEVEL, gpi.Level);
    cv.put(Friends.PROGRESS, gpi.Progress);
    cv.put(Friends.ONLINE_STATUS, gpi.OnlineStatus);
    cv.put(Friends.TROPHIES_PLATINUM, gpi.PlatinumTrophies);
    cv.put(Friends.TROPHIES_GOLD, gpi.GoldTrophies);
    cv.put(Friends.TROPHIES_SILVER, gpi.SilverTrophies);
    cv.put(Friends.TROPHIES_BRONZE, gpi.BronzeTrophies);
    cv.put(Friends.PLAYING, gpi.Playing);
    cv.put(Friends.LAST_UPDATED, updated);

    if (friendId < 0) {
        // New
        cv.put(Friends.ACCOUNT_ID, account.getId());
        cr.insert(Friends.CONTENT_URI, cv);
    } else {
        cr.update(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), cv, null, null);
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Friend page processing", started);

    cr.notifyChange(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), null);
}

From source file:com.akop.bach.parser.PsnEuParser.java

@SuppressLint("DefaultLocale")
@Override/* w  ww  .  j a  v a 2  s .com*/
protected void parseGames(PsnAccount account) throws ParserException, IOException {
    long started = System.currentTimeMillis();
    boolean keepGoing = true;
    List<ContentValues> cvList = new ArrayList<ContentValues>();

    for (int startIndex = 0; keepGoing; startIndex += 16) {
        String url = String.format(URL_GAMES, startIndex);
        String page = getResponse(url);

        keepGoing = parseGamePage(startIndex, page, cvList);
    }

    final long accountId = account.getId();
    ContentResolver cr = mContext.getContentResolver();
    String[] queryParams = new String[1];
    Cursor c;
    long updated = System.currentTimeMillis();
    List<ContentValues> newCvs = new ArrayList<ContentValues>(100);

    // Check to see if we already have a record of this game
    for (ContentValues cv : cvList) {
        queryParams[0] = cv.getAsString(Games.UID);
        c = cr.query(Games.CONTENT_URI, GAMES_PROJECTION,
                Games.ACCOUNT_ID + "=" + accountId + " AND " + Games.UID + "=?", queryParams, null);

        try {
            if (c == null || !c.moveToFirst()) // New game
            {
                cv.put(Games.ACCOUNT_ID, accountId);
                cv.put(Games.TROPHIES_DIRTY, 1);
                cv.put(Games.LAST_UPDATED, updated);

                newCvs.add(cv);
            } else // Existing game
            {
                boolean isDirty = false;
                long gameId = c.getLong(COLUMN_GAME_ID);

                if (c.getInt(COLUMN_GAME_PROGRESS) != cv.getAsInteger(Games.PROGRESS))
                    isDirty = true;
                if (c.getInt(COLUMN_GAME_BRONZE) != cv.getAsInteger(Games.UNLOCKED_BRONZE))
                    isDirty = true;
                if (c.getInt(COLUMN_GAME_SILVER) != cv.getAsInteger(Games.UNLOCKED_SILVER))
                    isDirty = true;
                if (c.getInt(COLUMN_GAME_GOLD) != cv.getAsInteger(Games.UNLOCKED_GOLD))
                    isDirty = true;
                if (c.getInt(COLUMN_GAME_PLATINUM) != cv.getAsInteger(Games.UNLOCKED_PLATINUM))
                    isDirty = true;

                if (isDirty)
                    cv.put(Games.TROPHIES_DIRTY, 1);

                cv.put(Games.LAST_UPDATED, updated);

                cr.update(Games.CONTENT_URI, cv, Games._ID + "=" + gameId, null);
            }
        } finally {
            if (c != null)
                c.close();
        }
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Game page processing", started);

    if (newCvs.size() > 0) {
        ContentValues[] cvs = new ContentValues[newCvs.size()];
        newCvs.toArray(cvs);

        cr.bulkInsert(Games.CONTENT_URI, cvs);

        if (App.getConfig().logToConsole())
            displayTimeTaken("Game page insertion", started);
    }

    account.refresh(Preferences.get(mContext));
    account.setLastGameUpdate(System.currentTimeMillis());
    account.save(Preferences.get(mContext));

    cr.notifyChange(Games.CONTENT_URI, null);
}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

private void photoSucess(Intent intent) {
    //URI????URI?URI??
    //???try-catch???
    Uri uri = intent.getData();//  ww  w . j a v a2  s .c  o m
    if (null == uri) {
        uri = mImageUri;
    }
    ContentResolver resolver = getContext().getContentResolver();
    XPathResolver pathResolver = new XPathResolver(null == uri ? null : uri.toString(), "", getContext());
    Bitmap bitmap = null;
    try {
        if (!mAllowEdit) {
            String path = pathResolver.resolve();
            if (!XStringUtils.isEmptyString(path)) {
                bitmap = XUtils.decodeBitmap(path);
            }
        } else {
            //??????Android???
            bitmap = intent.getExtras().getParcelable("data");

            //?????URI
            if (bitmap == null) {
                bitmap = getCroppedBitmap(intent);
            }
        }
    } catch (OutOfMemoryError e) {
        mCallbackCtx.error("OutOfMemoryError when decode image.");
        return;
    }
    if (mDestType == DATA_URL) {
        int rotate = 0;
        String[] cols = { MediaStore.Images.Media.ORIENTATION };
        Cursor cursor = resolver.query(uri, cols, null, null, null);
        if (null != cursor) {
            cursor.moveToPosition(0);
            rotate = cursor.getInt(0);
            cursor.close();
        }
        if (0 != rotate) {
            Matrix matrix = new Matrix();
            matrix.setRotate(rotate);
            bitmap = bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }
        bitmap = scaleBitmap(bitmap);
        processPicture(bitmap);
        bitmap.recycle();
        bitmap = null;
        System.gc();
    } else if (mTargetHeight > 0 && mTargetWidth > 0) {
        try {
            Bitmap scaleBitmap = scaleBitmap(bitmap);

            String fileName = XConfiguration.getInstance().getWorkDirectory() + RESIZED_PIC_NAME;
            OutputStream os = new FileOutputStream(fileName);
            scaleBitmap.compress(Bitmap.CompressFormat.JPEG, mQuality, os);
            os.close();

            bitmap.recycle();
            bitmap = null;
            scaleBitmap.recycle();
            scaleBitmap = null;

            mCallbackCtx.success("file://" + fileName + "?" + System.currentTimeMillis());
            System.gc();
        } catch (Exception e) {
            mCallbackCtx.error("Error retrieving image.");
            return;
        }
    } else {
        mCallbackCtx.success(XConstant.FILE_SCHEME + pathResolver.resolve());
    }
}

From source file:com.viktorrudometkin.burramys.fragment.EntriesListFragment.java

public void markAllAsRead() {
    if (mEntriesCursorAdapter != null) {
        Snackbar snackbar = Snackbar/*from  w w w . j  a va  2s  . c om*/
                .make(getActivity().findViewById(R.id.coordinator_layout), R.string.marked_as_read,
                        Snackbar.LENGTH_LONG)
                .setActionTextColor(ContextCompat.getColor(getActivity(), R.color.light_theme_color_primary))
                .setAction(R.string.undo, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new Thread() {
                            @Override
                            public void run() {
                                if (mJustMarkedAsReadEntries != null && !mJustMarkedAsReadEntries.isClosed()) {
                                    ArrayList<Integer> ids = new ArrayList<>();
                                    while (mJustMarkedAsReadEntries.moveToNext()) {
                                        ids.add(mJustMarkedAsReadEntries.getInt(0));
                                    }
                                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                                    String where = BaseColumns._ID + " IN (" + TextUtils.join(",", ids) + ')';
                                    cr.update(FeedData.EntryColumns.CONTENT_URI,
                                            FeedData.getUnreadContentValues(), where, null);

                                    mJustMarkedAsReadEntries.close();
                                }
                            }
                        }.start();
                    }
                });
        snackbar.getView().setBackgroundResource(R.color.material_grey_900);
        snackbar.show();

        new Thread() {
            @Override
            public void run() {
                ContentResolver cr = MainApplication.getContext().getContentResolver();
                String where = EntryColumns.WHERE_UNREAD + Constants.DB_AND + '(' + EntryColumns.FETCH_DATE
                        + Constants.DB_IS_NULL + Constants.DB_OR + EntryColumns.FETCH_DATE + "<="
                        + mListDisplayDate + ')';
                if (mJustMarkedAsReadEntries != null && !mJustMarkedAsReadEntries.isClosed()) {
                    mJustMarkedAsReadEntries.close();
                }
                mJustMarkedAsReadEntries = cr.query(mCurrentUri, new String[] { BaseColumns._ID }, where, null,
                        null);
                cr.update(mCurrentUri, FeedData.getReadContentValues(), where, null);
            }
        }.start();

        // If we are on "all items" uri, we can remove the notification here
        if (mCurrentUri != null && Constants.NOTIF_MGR != null && (EntryColumns.CONTENT_URI.equals(mCurrentUri)
                || EntryColumns.UNREAD_ENTRIES_CONTENT_URI.equals(mCurrentUri))) {
            Constants.NOTIF_MGR.cancel(0);
        }
    }
}

From source file:net.kidlogger.kidlogger.KLService.java

private String getNameFromContacts(String number, boolean record) {
    ContentResolver cr = getContentResolver();
    // Get Name from Contacts
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    Cursor curId = cr.query(uri, new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
    if (curId == null) {
        if (record)
            return "unknown";
        else/*from w  ww.j a va 2  s. co m*/
            return number + " unknown";
    }

    if (curId.getCount() > 0) {
        while (curId.moveToNext()) {
            String name = curId.getString(curId.getColumnIndex(PhoneLookup.DISPLAY_NAME));
            if (!name.equals("")) {
                if (record)
                    return name;
                else
                    return number + " " + name;
            }
        }
    }
    curId.close();

    if (record)
        return "unknown";
    else
        return number + " unknown";
}

From source file:com.chaqianma.jd.fragment.CompanyInfoFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
        case REQUEST_SDK_IMGS:
            if (data != null && data.getData() != null) {
                Uri imgUri = data.getData();
                ContentResolver resolver = getActivity().getContentResolver();
                String[] pojo = { MediaStore.Images.Media.DATA };
                Cursor cursor = null;
                try {
                    cursor = resolver.query(imgUri, pojo, null, null, null);
                    if (cursor != null && cursor.getCount() > 0) {
                        int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        cursor.moveToFirst();
                        new Thread(new BaseFragment.ImgRunable(cursor.getString(colunm_index),
                                Constants.BUSINESS_INFO, fileType, selCompanyIdxTag, new UpdateUIHandler()))
                                        .start();
                    } else {
                        JDToast.showLongText(getActivity(), "");
                    }/*  ww  w.ja  v  a  2 s . c o m*/
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            }
            break;
        case REQUEST_TAKE_PHOTO:
            new Thread(new BaseFragment.ImgRunable(Constants.TEMPPATH, Constants.BUSINESS_INFO, fileType,
                    selCompanyIdxTag, new UpdateUIHandler())).start();
            break;
        default:
            break;
        }
    }
}

From source file:com.hhunj.hhudata.ForegroundService.java

private String updatedb(List<SearchBookContentsResult> items) {

    String sMessage = "";
    ContentResolver resolver = getApplicationContext().getContentResolver();

    ContentValues values = new ContentValues();

    for (int i = 0; i < items.size(); i++) {

        SearchBookContentsResult res = items.get(i);
        if (res == null)
            continue;
        long stationid = Long.parseLong(res.getPageNumber());

        values.put(NotePad.Notes.TITLE, res.getName());
        values.put(NotePad.Notes.NOTE, "");

        values.put(NotePad.Notes.LONGITUTE, 108.0);
        values.put(NotePad.Notes.LATITUDE, 32.0);
        values.put(NotePad.Notes.SPEED, 55);
        values.put(NotePad.Notes.ALTITUDE, 55);

        values.put(NotePad.Notes.CREATEDDATE, res.getRectime().getTime());

        values.put(NotePad.Notes._ID, stationid);// id

        Uri urlNote = NotePad.Notes.CONTENT_URI;

        Uri myUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, stationid);

        //?????/* ww w  .  ja va  2s.  c  o m*/
        Cursor cur = resolver.query(myUri, NotePad.Notes.PROJECTION, null, null, null);
        if (cur == null) {
            // 
        }
        if (cur != null && cur.moveToFirst()) {
            long id = cur.getLong(NotePad.Notes._ID_COLUMN);
            Date oldtime = new Date(cur.getLong(cur.getColumnIndex(NotePad.Notes.CREATEDDATE)));
            boolean oldalarm = (cur.getInt(NotePad.Notes.ALARM_COLUMN) == 0) ? false : true;

            long dif = (res.getRectime().getTime() - oldtime.getTime()) / (60 * 1000);

            // 
            dif = ((new Date()).getTime() - oldtime.getTime()) / (60 * 1000);
            boolean newalarm = false;//
            if (dif > m_alamspan) {
                // ...
                if (oldalarm == false) {
                    Log.w(TAG, "over time err--------");
                    // String phoneNumber ="13338620269";
                    sMessage += "---" + id + "---";
                    newalarm = true;
                } else {
                    newalarm = true;
                }

            }

            values.put(NotePad.Notes.ALARM, newalarm);
            int count = resolver.update(myUri, values, null, null);
            if (count == 0) {

            }

        } else {
            values.put(NotePad.Notes.ALARM, false);
            try {
                myUri = resolver.insert(urlNote, values);
            } catch (IllegalArgumentException e) {
                throw e;
            } catch (SQLException e2) {
                int aa = 0;
                throw e2;
            }
        }
    }
    return sMessage;
}