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.ktouch.kdc.launcher4.camera.ui.ReviewDrawer.java

/**
 * Clears the list of images and reload it from the Gallery (MediaStore)
 * This method is synchronous, see updateFromGallery for the threaded one.
 *
 * @param images True to get images, false to get videos
 * @param scrollPos Position to scroll to, or 0 to get latest image
 *//*from w  ww.  j  a  va 2 s .co m*/
public void updateFromGallerySynchronous(final boolean images, final int scrollPos) {
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            synchronized (mImagesLock) {
                mImages.clear();
                mImagesListAdapter.notifyDataSetChanged();
            }

            String[] columns;
            String orderBy;
            if (images) {
                columns = new String[] { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
                orderBy = MediaStore.Images.Media.DATE_TAKEN + " ASC";
            } else {
                columns = new String[] { MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID };
                orderBy = MediaStore.Video.Media.DATE_TAKEN + " ASC";
            }

            // Select only the images that has been taken from the Camera
            Context ctx = getContext();
            if (ctx == null)
                return;
            ContentResolver cr = ctx.getContentResolver();
            if (cr == null) {
                Log.e(TAG, "No content resolver!");
                return;
            }

            Cursor cursor;

            if (images) {
                cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
                        MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " LIKE ?",
                        new String[] { GALLERY_CAMERA_BUCKET }, orderBy);
            } else {
                cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns,
                        MediaStore.Video.Media.BUCKET_DISPLAY_NAME + " LIKE ?",
                        new String[] { GALLERY_CAMERA_BUCKET }, orderBy);
            }

            if (cursor == null) {
                Log.e(TAG, "Null cursor from MediaStore!");
                return;
            }

            final int imageColumnIndex = cursor
                    .getColumnIndex(images ? MediaStore.Images.Media._ID : MediaStore.Video.Media._ID);

            for (int i = 0; i < cursor.getCount(); i++) {
                cursor.moveToPosition(i);

                int id = cursor.getInt(imageColumnIndex);
                if (mReviewedImageId <= 0) {
                    mReviewedImageId = id;
                }
                addImageToList(id);
                mImagesListAdapter.notifyDataSetChanged();
            }

            cursor.close();

            if (scrollPos < mImages.size()) {
                mViewPager.setCurrentItem(scrollPos + 1, false);
                mViewPager.setCurrentItem(scrollPos, true);
            }
        }
    });
}

From source file:com.shafiq.mytwittle.view.HomeActivity.java

void onCreateHandleIntents() {

    boolean turnSoftKeyboardOff = true;

    Intent intent = getIntent();/*w  ww  .  j ava  2s. c o m*/
    if (intent.getAction() == Intent.ACTION_SEND) {

        Bundle extras = intent.getExtras();
        String type = intent.getType();
        if (type.equals("text/plain") == true) {

            String shareString = extras.getString(Intent.EXTRA_TEXT);
            if (extras.containsKey(Intent.EXTRA_TEXT)) {
                shareString = extras.getString(Intent.EXTRA_SUBJECT) + " " + shareString;
            }
            beginShareStatus(shareString);

            turnSoftKeyboardOff = false;
        } else if (type.contains("image/")) {
            // From http://stackoverflow.com/a/2641363/328679
            if (extras.containsKey(Intent.EXTRA_STREAM)) {
                Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
                String scheme = uri.getScheme();
                if (scheme.equals("content")) {
                    ContentResolver contentResolver = getContentResolver();
                    Cursor cursor = contentResolver.query(uri, null, null, null, null);
                    cursor.moveToFirst();
                    try {
                        String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.DATA));
                        beginShareImage(imagePath);
                    } catch (java.lang.IllegalArgumentException e) {
                        Toast.makeText(this, R.string.picture_attach_error, Toast.LENGTH_SHORT).show();
                    }

                    turnSoftKeyboardOff = false;
                }
            }
        }
    }

    if (turnSoftKeyboardOff == true) {
        // Turn the soft-keyboard off. For some reason it wants to appear on
        // screen by default when coming back from multitasking...
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
}

From source file:com.android.mail.utils.NotificationUtils.java

private static ArrayList<Long> findContacts(Context context, Collection<String> addresses) {
    ArrayList<String> whereArgs = new ArrayList<String>();
    StringBuilder whereBuilder = new StringBuilder();
    String[] questionMarks = new String[addresses.size()];

    whereArgs.addAll(addresses);/*from   w w w.j  a  v  a  2 s . co  m*/
    Arrays.fill(questionMarks, "?");
    whereBuilder.append(Email.DATA1 + " IN (").append(TextUtils.join(",", questionMarks)).append(")");

    ContentResolver resolver = context.getContentResolver();
    Cursor c = resolver.query(Email.CONTENT_URI, new String[] { Email.CONTACT_ID }, whereBuilder.toString(),
            whereArgs.toArray(new String[0]), null);

    ArrayList<Long> contactIds = new ArrayList<Long>();
    if (c == null) {
        return contactIds;
    }
    try {
        while (c.moveToNext()) {
            contactIds.add(c.getLong(0));
        }
    } finally {
        c.close();
    }
    return contactIds;
}

From source file:com.tweetlanes.android.core.view.HomeActivity.java

void onCreateHandleIntents() {

    boolean turnSoftKeyboardOff = true;

    Intent intent = getIntent();//from  w ww.j  a  va2  s  . c o m

    Bundle extras = intent.getExtras();

    if (extras != null) {
        String type = intent.getType();
        if (intent.getAction() == Intent.ACTION_SEND && type != null) {

            if (type.equals("text/plain") && extras.containsKey(Intent.EXTRA_TEXT)) {

                String shareString = extras.getString(Intent.EXTRA_TEXT);
                if (extras.containsKey(Intent.EXTRA_SUBJECT)) {
                    shareString = extras.getString(Intent.EXTRA_SUBJECT) + " " + shareString;
                }
                beginShareStatus(shareString);

                turnSoftKeyboardOff = false;

            } else if (type.contains("image/")) {
                // From http://stackoverflow.com/a/2641363/328679
                if (extras.containsKey(Intent.EXTRA_STREAM)) {
                    Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
                    String scheme = uri.getScheme();
                    if (scheme.equals("content")) {
                        ContentResolver contentResolver = getContentResolver();
                        Cursor cursor = contentResolver.query(uri, null, null, null, null);
                        cursor.moveToFirst();
                        try {
                            String imagePath = cursor
                                    .getString(cursor.getColumnIndexOrThrow(Images.Media.DATA));
                            beginShareImage(imagePath);
                        } catch (java.lang.IllegalArgumentException e) {
                            Toast.makeText(this, R.string.picture_attach_error, Toast.LENGTH_SHORT).show();
                        } finally {
                            cursor.close();
                            cursor = null;
                        }

                        turnSoftKeyboardOff = false;
                    }
                }
            }
        }
    }

    if (turnSoftKeyboardOff) {
        // Turn the soft-keyboard off. For some reason it wants to appear on
        // screen by default when coming back from multitasking...
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
}

From source file:com.android.contacts.group.GroupMembersFragment.java

private void sendToGroup(long[] ids, String sendScheme, String title) {
    if (ids == null || ids.length == 0)
        return;// www .ja v  a 2s  .  co m

    // Get emails or phone numbers
    // contactMap <contact_id, contact_data>
    final Map<String, ContactDataHelperClass> contactMap = new HashMap<>();
    // itemList <item_data>
    final List<String> itemList = new ArrayList<>();
    final String sIds = GroupUtil.convertArrayToString(ids);
    final String select = (ContactsUtils.SCHEME_MAILTO.equals(sendScheme) ? Query.EMAIL_SELECTION
            : Query.PHONE_SELECTION) + " AND " + ContactsContract.Data.CONTACT_ID + " IN (" + sIds + ")";
    final ContentResolver contentResolver = getContext().getContentResolver();
    final Cursor cursor = contentResolver.query(ContactsContract.Data.CONTENT_URI,
            ContactsUtils.SCHEME_MAILTO.equals(sendScheme) ? Query.EMAIL_PROJECTION : Query.PHONE_PROJECTION,
            select, null, null);

    if (cursor == null) {
        return;
    }

    try {
        cursor.moveToPosition(-1);
        while (cursor.moveToNext()) {
            final String contactId = cursor.getString(Query.CONTACT_ID);
            final String itemId = cursor.getString(Query.ITEM_ID);
            final boolean isPrimary = cursor.getInt(Query.PRIMARY) != 0;
            final int timesUsed = cursor.getInt(Query.TIMES_USED);
            final String data = cursor.getString(Query.DATA1);

            if (!TextUtils.isEmpty(data)) {
                final ContactDataHelperClass contact;
                if (!contactMap.containsKey(contactId)) {
                    contact = new ContactDataHelperClass();
                    contactMap.put(contactId, contact);
                } else {
                    contact = contactMap.get(contactId);
                }
                contact.addItem(itemId, timesUsed, isPrimary);
                itemList.add(data);
            }
        }
    } finally {
        cursor.close();
    }

    // Start picker if a contact does not have a default
    for (ContactDataHelperClass i : contactMap.values()) {
        if (!i.hasDefaultItem()) {
            // Build list of default selected item ids
            final List<Long> defaultSelection = new ArrayList<>();
            for (ContactDataHelperClass j : contactMap.values()) {
                final String selectionItemId = j.getDefaultSelectionItemId();
                if (selectionItemId != null) {
                    defaultSelection.add(Long.parseLong(selectionItemId));
                }
            }
            final long[] defaultSelectionArray = Longs.toArray(defaultSelection);
            startSendToSelectionPickerActivity(ids, defaultSelectionArray, sendScheme, title);
            return;
        }
    }

    if (itemList.size() == 0 || contactMap.size() < ids.length) {
        Toast.makeText(getContext(),
                ContactsUtils.SCHEME_MAILTO.equals(sendScheme)
                        ? getString(R.string.groupSomeContactsNoEmailsToast)
                        : getString(R.string.groupSomeContactsNoPhonesToast),
                Toast.LENGTH_LONG).show();
    }

    if (itemList.size() == 0) {
        return;
    }

    final String itemsString = TextUtils.join(",", itemList);
    GroupUtil.startSendToSelectionActivity(this, itemsString, sendScheme, title);
}

From source file:com.charabia.SmsViewActivity.java

@Override
public void onResume() {
    super.onResume();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefPhoneNumber = prefs.getString(PreferencesActivity.PHONE_NUMBER, null);
    if (prefPhoneNumber == null || prefPhoneNumber.length() <= 0) {

        Intent intent;/*from   w w  w .ja v  a  2s  .  co m*/

        intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.setClassName(this, PreferencesActivity.class.getName());
        startActivity(intent);

        intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.setClassName(this, WebViewActivity.class.getName());
        intent.setData(Uri.parse(WebViewActivity.getBaseUrl(this, "/help", "enter_phone_number.html")));
        startActivity(intent);

        //Attempt to retrieve old keys

        android.content.ContentResolver cr = getContentResolver();
        android.database.Cursor cursor = cr.query(Data.CONTENT_URI,
                new String[] { Data._ID, Tools.PHONE, Tools.KEY }, Data.MIMETYPE + "=?",
                new String[] { Tools.CONTENT_ITEM_TYPE }, null);
        while (cursor.moveToNext()) {
            try {
                tools.updateOrCreateContactKey(cursor.getString(cursor.getColumnIndex(Tools.PHONE)),
                        Base64.decode(cursor.getString(cursor.getColumnIndex(Tools.KEY)), Base64.DEFAULT),
                        false);

                cr.delete(ContentUris.withAppendedId(Data.CONTENT_URI,
                        cursor.getLong(cursor.getColumnIndex(Data._ID))), null, null);
            } catch (NoContactException e) {
                e.printStackTrace();
                Toast.makeText(this, "No contact for " + cursor.getColumnIndex(Tools.PHONE), Toast.LENGTH_SHORT)
                        .show();
            }

        }
    }
}

From source file:com.bt.download.android.gui.Librarian.java

/**
 * /*from www .ja  va  2s  . c  om*/
 * @param fileType
 * @param onlyShared - If false, forces getting all files, shared or unshared. 
 * @return
 */
public int getNumFiles(byte fileType, boolean onlyShared) {
    TableFetcher fetcher = TableFetchers.getFetcher(fileType);

    if (cache[fileType].cacheValid(onlyShared)) {
        return cache[fileType].getCount(onlyShared);
    }

    Cursor c = null;

    int result = 0;
    int numFiles = 0;

    try {
        ContentResolver cr = context.getContentResolver();
        c = cr.query(fetcher.getContentUri(), new String[] { BaseColumns._ID }, null, null, null);
        numFiles = c != null ? c.getCount() : 0;
    } catch (Exception e) {
        Log.e(TAG, "Failed to get num of files", e);
    } finally {
        if (c != null) {
            c.close();
        }
    }

    result = onlyShared ? (getSharedFiles(fileType).size()) : numFiles;

    updateCacheNumFiles(fileType, result, onlyShared);

    return result;
}

From source file:com.bt.download.android.gui.Librarian.java

private Pair<List<Integer>, List<String>> getAllFiles(byte fileType) {
    Pair<List<Integer>, List<String>> result = new Pair<List<Integer>, List<String>>(new ArrayList<Integer>(),
            new ArrayList<String>());

    Cursor c = null;/*w  w  w .jav  a 2s .  c  o m*/

    try {
        TableFetcher fetcher = TableFetchers.getFetcher(fileType);

        ContentResolver cr = context.getContentResolver();

        c = cr.query(fetcher.getContentUri(), new String[] { BaseColumns._ID, MediaColumns.DATA }, null, null,
                BaseColumns._ID);

        if (c != null) {
            while (c.moveToNext()) {
                result.first.add(c.getInt(0));
                result.second.add(c.getString(1));
            }
        }
    } catch (Throwable e) {
        Log.e(TAG, "General failure getting all files", e);
    } finally {
        if (c != null) {
            c.close();
        }
    }

    return result;
}

From source file:com.android.dialer.voicemail.VoicemailPlaybackPresenter.java

private boolean queryHasContent(Uri voicemailUri) {
    if (voicemailUri == null || mContext == null) {
        return false;
    }/*from   ww  w . j  av a2s.  c  o  m*/

    ContentResolver contentResolver = mContext.getContentResolver();
    Cursor cursor = contentResolver.query(voicemailUri, null, null, null, null);
    try {
        if (cursor != null && cursor.moveToNext()) {
            int duration = cursor.getInt(cursor.getColumnIndex(VoicemailContract.Voicemails.DURATION));
            // Convert database duration (seconds) into mDuration (milliseconds)
            mDuration.set(duration > 0 ? duration * 1000 : 0);
            return cursor.getInt(cursor.getColumnIndex(VoicemailContract.Voicemails.HAS_CONTENT)) == 1;
        }
    } finally {
        MoreCloseables.closeQuietly(cursor);
    }
    return false;
}