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:jp.ac.tokushima_u.is.ll.io.LanguageJsonHandler.java

public ArrayList<ContentProviderOperation> parse(ContentResolver resolver) {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    Uri uri = Languages.CONTENT_URI;
    String sortOrder = SyncColumns.UPDATED + " desc";
    Cursor cursor = resolver.query(uri, LanguagesQuery.PROJECTION, null, null, sortOrder);
    try {/*from   www .  java  2  s .  c  om*/
        if (cursor.moveToFirst()) {
            Log.d(TAG, "Language has been inserted");
            int count = cursor.getCount();
            if (count > 3) {
                return batch;
            }
        }
    } finally {
        cursor.close();
    }

    HttpPost httpPost = new HttpPost(this.systemUrl + this.syncServiceUrl + this.languageSearchUrl);
    try {
        DefaultHttpClient client = HttpClientFactory.createHttpClient();
        MultipartEntity params = new MultipartEntity();
        httpPost.setEntity(params);
        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            String result = convertStreamToString(instream);
            instream.close();
            JSONObject json = new JSONObject(result);
            if (json != null) {
                JSONArray array = json.getJSONArray("languages");
                if (array != null) {
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject o = array.getJSONObject(i);
                        String languageId = o.getString("id");
                        if (languageId == null || languageId.length() <= 0)
                            continue;

                        ContentProviderOperation.Builder builder = ContentProviderOperation
                                .newInsert(Languages.CONTENT_URI);

                        builder.withValue(Languages.LANGUAGE_ID, languageId);
                        if (o.getString("code") != null && o.getString("code").length() > 0
                                && !"null".equals(o.getString("code")))
                            builder.withValue(Languages.CODE, o.getString("code"));
                        if (o.getString("name") != null && o.getString("name").length() > 0
                                && !"null".equals(o.getString("name")))
                            builder.withValue(Languages.NAME, o.getString("name"));
                        builder.withValue(SyncColumns.UPDATED, Calendar.getInstance().getTimeInMillis());
                        batch.add(builder.build());
                    }
                }
            }
        }
    } catch (Exception e) {
        Log.d(TAG, "exception occured", e);
    }

    return batch;
}

From source file:com.adampash.contactSearch.ContactsSearchModule.java

@Kroll.method
private TiBlob fetchThumbnail(int thumbnailId) {
    ContentResolver contentResolver = appContext.getContentResolver();

    String[] PHOTO_BITMAP_PROJECTION = new String[] { ContactsContract.CommonDataKinds.Photo.PHOTO };
    Uri uri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, thumbnailId);
    Cursor cursor = contentResolver.query(uri, PHOTO_BITMAP_PROJECTION, null, null, null);

    try {//from  w ww .j ava  2  s  .c o m
        Bitmap thumbnail = null;
        if (cursor.moveToFirst()) {
            byte[] thumbnailBytes = cursor.getBlob(0);
            if (thumbnailBytes != null) {
                thumbnail = BitmapFactory.decodeByteArray(thumbnailBytes, 0, thumbnailBytes.length);
            }
        }
        /* return thumbnail; */
        return TiBlob.blobFromImage(thumbnail);
    } finally {
        cursor.close();
    }

}

From source file:com.github.shareme.gwschips.library.BaseRecipientAdapter.java

private static void fetchPhotoAsync(final RecipientEntry entry, final Uri photoThumbnailUri,
        final BaseAdapter adapter, final ContentResolver mContentResolver) {
    final AsyncTask<Void, Void, byte[]> photoLoadTask = new AsyncTask<Void, Void, byte[]>() {
        @Override/* w  w  w . j  a va 2 s  .c  o m*/
        protected byte[] doInBackground(Void... params) {
            // First try running a query. Images for local contacts are
            // loaded by sending a query to the ContactsProvider.
            final Cursor photoCursor = mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION, null,
                    null, null);
            if (photoCursor != null) {
                try {
                    if (photoCursor.moveToFirst()) {
                        return photoCursor.getBlob(PhotoQuery.PHOTO);
                    }
                } finally {
                    photoCursor.close();
                }
            } else {
                // If the query fails, try streaming the URI directly.
                // For remote directory images, this URI resolves to the
                // directory provider and the images are loaded by sending
                // an openFile call to the provider.
                try {
                    InputStream is = mContentResolver.openInputStream(photoThumbnailUri);
                    if (is != null) {
                        byte[] buffer = new byte[BUFFER_SIZE];
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        try {
                            int size;
                            while ((size = is.read(buffer)) != -1) {
                                baos.write(buffer, 0, size);
                            }
                        } finally {
                            is.close();
                        }
                        return baos.toByteArray();
                    }
                } catch (IOException ex) {
                    // ignore
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(final byte[] photoBytes) {
            entry.setPhotoBytes(photoBytes);
            if (photoBytes != null) {
                mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
                if (adapter != null)
                    adapter.notifyDataSetChanged();
            }
        }
    };
    photoLoadTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}

From source file:com.example.android.ennis.barrett.popularmovies.DetailFragment.java

/**
 * Sets all the views to related id.//  w  w  w .j  av a 2 s . co m
 * @param _id The id of the movie
 */
private void setDetails(long _id) {
    /*
     * get references
     */
    TextView title = (TextView) mRootView.findViewById(R.id.original_title);
    TextView overview = (TextView) mRootView.findViewById(R.id.overview);
    TextView date = (TextView) mRootView.findViewById(R.id.date);
    TextView voteAverage2 = (TextView) mRootView.findViewById(R.id.vote_average2);
    ImageView poster = (ImageView) mRootView.findViewById(R.id.poster);
    RatingBar voteAverage = (RatingBar) mRootView.findViewById(R.id.vote_average);
    LinearLayout videos = (LinearLayout) mRootView.findViewById(R.id.videos);
    LinearLayout reviews = (LinearLayout) mRootView.findViewById(R.id.reviews);
    CompoundButton isFavorite = (CompoundButton) mRootView.findViewById(R.id.favorite);

    ContentResolver contentResolver = getActivity().getContentResolver();

    /*
     * Queries the movies table
     */
    Cursor cursor = contentResolver.query(TMDbContract.Movies.URI, null, TMDbContract.Movies.ID + " = ?",
            new String[] { mID + "" }, null);
    cursor.moveToFirst();

    /*
     * sets most views to the movie
     */
    title.setText(cursor.getString(cursor.getColumnIndex(TMDbContract.Movies.ORIGINAL_TITLE)));

    overview.setText(cursor.getString(cursor.getColumnIndex(TMDbContract.Movies.OVERVIEW)));

    date.setText(cursor.getString(cursor.getColumnIndex(TMDbContract.Movies.RELEASE_DATE)));

    // Setups up the poster
    String posterURLString = "http://image.tmdb.org/t/p/w185/"
            + cursor.getString(cursor.getColumnIndex(TMDbContract.Movies.POSTER));
    Log.v(TAG, posterURLString);
    Picasso.with(getActivity()).load(posterURLString).into(poster);

    String bool = cursor.getString(cursor.getColumnIndex(TMDbContract.Movies.IS_FAVORITE));

    isFavorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ContentValues value = new ContentValues();
            String isFavorite = "0";
            if (((CompoundButton) v).isChecked()) {
                isFavorite = "1";
            }

            value.put(TMDbContract.Movies.IS_FAVORITE, isFavorite);
            int num = getActivity().getContentResolver().update(TMDbContract.Movies.URI, value,
                    TMDbContract.Movies._ID + " = ?", new String[] { Long.toString(mID) });
        }
    });

    //short circuit logic stops app from crashing..So don't reverse the expression
    if (bool != null && bool.equals("1")) {
        isFavorite.setChecked(true);
    } else {
        isFavorite.setChecked(false);
    }

    //Set up the RatingBar and the TextView with the rating
    float vote = cursor.getFloat(cursor.getColumnIndex(TMDbContract.Movies.VOTE_AVERAGE));
    voteAverage2.setText(vote + " / 10 ");
    vote /= 2;
    Log.v(TAG, vote + "");
    voteAverage.setRating(vote);
    Log.v(TAG, voteAverage.getRating() + "");

    /*
     * Set up the videos LinearLayout.
     * Queries the table and then creates TextViews to display the results
     */
    Cursor cursorVideos = contentResolver.query(TMDbContract.Videos.URI, null,
            TMDbContract.Videos.MOVIE_IDS + " = ?",
            new String[] { cursor.getString(cursor.getColumnIndex(TMDbContract.Movies.MOVIE_ID)) }, null);
    VideoCursorAdapter adapter = new VideoCursorAdapter(getActivity(), R.layout.video_card, cursorVideos);

    //loop to create TextViews to display the results
    for (int i = 0; i < adapter.getCount(); i++) {
        View view = adapter.getView(i, null, null);
        view.setOnClickListener(this);
        videos.addView(view);
    }

    /*
     * Set up the reviews LinearLayout.
     * Queries the table and then creates TextViews to display the results
     */
    Cursor cursorReviews = contentResolver.query(TMDbContract.Reviews.URI, null,
            TMDbContract.Reviews.MOVIE_IDS + " = ?",
            new String[] { cursor.getString(cursor.getColumnIndex(TMDbContract.Movies.MOVIE_ID)) }, null);

    if (cursorReviews.getCount() == 0) {
        mRootView.findViewById(R.id.reviews_header).setVisibility(View.GONE);
    } else {
        ReviewCursorAdapter adapter2 = new ReviewCursorAdapter(getActivity(), R.layout.review_card,
                cursorReviews);
        for (int i = 0; i < adapter2.getCount(); i++) {
            View view = adapter2.getView(i, null, null);
            reviews.addView(view);
        }
    }
}

From source file:org.maikelwever.droidpile.SendMailActivity.java

public ArrayList<AutocompleteContact> getContacts() {
    ArrayList<AutocompleteContact> alContacts = new ArrayList<AutocompleteContact>();
    ContentResolver contResv = getApplication().getContentResolver();
    Cursor cursor = contResv.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    if (cursor.moveToFirst()) {
        do {//from   w  w  w .  ja v a  2s . c  o  m
            String name = cursor
                    .getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

            AutocompleteContact contact = new AutocompleteContact(id, name);

            Cursor emails = contResv.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contact.id, null, null);
            while (emails.moveToNext()) {
                contact.addEmail(
                        emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
                break;
            }
            emails.close();

            alContacts.add(contact);

        } while (cursor.moveToNext());
    }

    cursor.close();
    return alContacts;
}

From source file:com.bangz.smartmute.RulelistFragment.java

@Override
public void onActivedButtonClick(long id, boolean bActivited) {
    //Cursor cursor = mAdapter.getCursor();

    LogUtils.LOGD(TAG, "Activited Button clicked. id: " + id + " Activited: " + bActivited);

    ContentResolver cr = getActivity().getContentResolver();
    Uri uri = ContentUris.withAppendedId(RulesColumns.CONTENT_URI, id);

    String[] projects = { RulesColumns.RULETYPE

    };//ww  w . j av a  2  s. c  o m
    Cursor cursor = cr.query(uri, projects, null, null, null);
    cursor.moveToFirst();
    int ruletype = cursor.getInt(cursor.getColumnIndex(RulesColumns.RULETYPE));

    ContentValues contentValues = new ContentValues();
    contentValues.put(RulesColumns.ACTIVATED, bActivited ? 1 : 0);
    cr.update(uri, contentValues, null, null);

    mAdapter.notifyDataSetChanged();

    if (ruletype == RulesColumns.RT_TIME) {
        if (bActivited == false)
            TimeRuleAlarmService.cancelScheduledAlarm(getActivity(), uri);
        else
            TimeRuleAlarmService.startScheduleAlarm(getActivity(), uri);
    } else if (ruletype == RulesColumns.RT_LOCATION) {
        //TODO cancel location mute
    }
}

From source file:com.ferid.app.frequentcontacts.selectnumber.SelectNumberActivity.java

/**
 * Get names and number of contacts/*from w w w .  j a  va  2 s  .  c o  m*/
 * @return
 */
private ArrayList<Contact> getNumbersList() {
    //keep track of added phones in order to handle redundancy
    ArrayList<String> addedPhoneNumbers = new ArrayList<>();
    //block to show already frequent ones
    ArrayList<Contact> frequentContacts = PrefsUtil.readFrequentContacts(this);
    if (frequentContacts != null) {
        for (Contact cnt : frequentContacts) {
            addedPhoneNumbers.add(cnt.getNumber());
        }
    }

    //contacts to be showed
    ArrayList<Contact> tmpList = new ArrayList<>();
    Contact contact;

    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

    if (cur != null) {
        try {
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    //names
                    int id = cur.getInt(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    final String name = cur
                            .getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                    if (Integer.parseInt(cur
                            .getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        //phones
                        Cursor phones = getContentResolver().query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER,
                                        ContactsContract.CommonDataKinds.Phone.TYPE },
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);

                        if (phones != null) {
                            while (phones.moveToNext()) {
                                String phoneNumber = phones.getString(
                                        phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                                //create a new Contact object
                                contact = new Contact();
                                contact.setId(id);
                                contact.setName(name);
                                contact.setNumber(phoneNumber.replace(" ", ""));

                                if (!TextUtils.isEmpty(contact.getNumber())
                                        && !addedPhoneNumbers.contains(contact.getNumber())) {

                                    tmpList.add(contact);
                                    addedPhoneNumbers.add(contact.getNumber());
                                }
                            }
                            phones.close();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cur.close();
        }
    }

    return tmpList;
}

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

public static void handleUpdateNotificationIntent(Context context, Intent intent) {
    final Uri accountUri = intent.getParcelableExtra(UIProvider.UpdateNotificationExtras.EXTRA_ACCOUNT);
    final Uri folderUri = intent.getParcelableExtra(UIProvider.UpdateNotificationExtras.EXTRA_FOLDER);
    final int unreadCount = intent.getIntExtra(UIProvider.UpdateNotificationExtras.EXTRA_UPDATED_UNREAD_COUNT,
            0);//from w  w w  . jav  a  2s  .  c  o  m
    final int unseenCount = intent.getIntExtra(UIProvider.UpdateNotificationExtras.EXTRA_UPDATED_UNSEEN_COUNT,
            0);

    final ContentResolver contentResolver = context.getContentResolver();

    final Cursor accountCursor = contentResolver.query(accountUri, UIProvider.ACCOUNTS_PROJECTION, null, null,
            null);

    if (accountCursor == null) {
        LogUtils.e(LOG_TAG, "Null account cursor for account " + accountUri);
        return;
    }

    com.tct.mail.providers.Account account = null;
    try {
        if (accountCursor.moveToFirst()) {
            account = com.tct.mail.providers.Account.builder().buildFrom(accountCursor);
        }
    } finally {
        accountCursor.close();
    }

    if (account == null) {
        LogUtils.d(LOG_TAG, "Tried to create a notification for a missing account " + accountUri);
        return;
    }

    final Cursor folderCursor = contentResolver.query(folderUri, UIProvider.FOLDERS_PROJECTION, null, null,
            null);

    if (folderCursor == null) {
        LogUtils.e(LOG_TAG, "Null folder cursor for account " + accountUri + ", mailbox " + folderUri);
        return;
    }

    Folder folder = null;
    try {
        if (folderCursor.moveToFirst()) {
            folder = new Folder(folderCursor);
        } else {
            LogUtils.e(LOG_TAG, "Empty folder cursor for account " + accountUri + ", mailbox " + folderUri);
            return;
        }
    } finally {
        folderCursor.close();
    }

    // TODO: we don't always want getAttention to be true, but we don't necessarily have a
    // good heuristic for when it should or shouldn't be.
    NotificationUtils.sendSetNewEmailIndicatorIntent(context, unreadCount, unseenCount, account, folder,
            true /* getAttention */);
}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MusicUtils.java

/**
 * Fills out the given submenu with items for "new playlist" and
 * any existing playlists. When the user selects an item, the
 * application will receive PLAYLIST_SELECTED with the Uri of
 * the selected playlist, NEW_PLAYLIST if a new playlist
 * should be created, and QUEUE if the "current playlist" was
 * selected./*w  w w.  j a  v  a  2  s  . co m*/
 *
 * @param context The context to use for creating the menu items
 * @param sub     The submenu to add the items to.
 */
public static void makePlaylistMenu(Context context, SubMenu sub) {
    String[] cols = new String[] { MediaStore.Audio.Playlists._ID, MediaStore.Audio.Playlists.NAME };
    ContentResolver resolver = context.getContentResolver();
    if (resolver == null) {
        System.out.println("resolver = null");
    } else {
        String whereclause = MediaStore.Audio.Playlists.NAME + " != ''";
        Cursor cur = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, cols, whereclause, null,
                MediaStore.Audio.Playlists.NAME);
        sub.clear();
        sub.add(1, Defs.QUEUE, 0, R.string.queue);
        sub.add(1, Defs.NEW_PLAYLIST, 0, R.string.new_playlist);
        if (cur != null && cur.getCount() > 0) {
            //sub.addSeparator(1, 0);
            cur.moveToFirst();
            while (!cur.isAfterLast()) {
                Intent intent = new Intent();
                intent.putExtra("playlist", cur.getLong(0));
                //                    if (cur.getInt(0) == mLastPlaylistSelected) {
                //                        sub.add(0, MusicBaseActivity.PLAYLIST_SELECTED, cur.getString(1)).setIntent(intent);
                //                    } else {
                sub.add(1, Defs.PLAYLIST_SELECTED, 0, cur.getString(1)).setIntent(intent);
                //                    }
                cur.moveToNext();
            }
        }
        if (cur != null) {
            cur.close();
        }
    }
}

From source file:com.andrew.apollo.menu.PlaylistDialog.java

private String makePlaylistName() {

    String template = getString(R.string.new_playlist_name_template);
    int num = 1;//from w ww  . j  a v  a 2 s. c  om

    String[] cols = new String[] { Audio.Playlists.NAME };
    ContentResolver resolver = getContentResolver();
    String whereclause = Audio.Playlists.NAME + " != ''";
    Cursor cursor = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, cols, whereclause, null,
            Audio.Playlists.NAME);

    if (cursor == null)
        return null;

    String suggestedname;
    suggestedname = String.format(template, num++);

    // Need to loop until we've made 1 full pass through without finding a
    // match. Looping more than once shouldn't happen very often, but will
    // happen if you have playlists named
    // "New Playlist 1"/10/2/3/4/5/6/7/8/9, where making only one pass would
    // result in "New Playlist 10" being erroneously picked for the new
    // name.
    boolean done = false;
    while (!done) {
        done = true;
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            String playlistname = cursor.getString(0);
            if (playlistname.compareToIgnoreCase(suggestedname) == 0) {
                suggestedname = String.format(template, num++);
                done = false;
            }
            cursor.moveToNext();
        }
    }
    cursor.close();
    return suggestedname;
}