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.example.android.miniweather.app.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city//from   w ww  .j  a  v a2 s  .c o  m
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {
    // Students: First, check if the location with this city name exists in the db
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI

    ContentResolver contentResolver = mContext.getContentResolver();
    Cursor cursor;
    long locationID;

    cursor = contentResolver.query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);

    if (cursor.moveToFirst()) {
        int locationIDIndex = cursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationID = cursor.getLong(locationIDIndex);
    } else {
        ContentValues newLocation = new ContentValues();
        Uri insertedUri;

        newLocation.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        newLocation.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        newLocation.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        newLocation.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        insertedUri = contentResolver.insert(WeatherContract.LocationEntry.CONTENT_URI, newLocation);

        locationID = ContentUris.parseId(insertedUri);

    }

    cursor.close();
    return locationID;
}

From source file:com.abcvoipsip.ui.calllog.CallLogDetailsFragment.java

/** Return the phone call details for a given call log URI. */
private PhoneCallDetails getPhoneCallDetailsForUri(Uri callUri) {
    ContentResolver resolver = getActivity().getContentResolver();
    Cursor callCursor = resolver.query(callUri, CALL_LOG_PROJECTION, null, null, null);
    try {//from   w w  w  .  jav  a2  s . c  o  m
        if (callCursor == null || !callCursor.moveToFirst()) {
            throw new IllegalArgumentException("Cannot find content: " + callUri);
        }

        // Read call log specifics.
        String number = callCursor.getString(NUMBER_COLUMN_INDEX);
        long date = callCursor.getLong(DATE_COLUMN_INDEX);
        long duration = callCursor.getLong(DURATION_COLUMN_INDEX);
        int callType = callCursor.getInt(CALL_TYPE_COLUMN_INDEX);
        Long accountId = callCursor.getLong(PROFILE_ID_COLUMN_INDEX);
        int statusCode = callCursor.getInt(STATUS_CODE_COLUMN_INDEX);
        String statusText = callCursor.getString(STATUS_TEXT_COLUMN_INDEX);

        // Formatted phone number.
        final CharSequence formattedNumber;
        // Read contact specifics.
        final CharSequence nameText;
        final int numberType;
        final CharSequence numberLabel;
        final Uri photoUri;
        final Uri lookupUri;
        // If this is not a regular number, there is no point in looking it
        // up in the contacts.
        CallerInfo info = CallerInfo.getCallerInfoFromSipUri(getActivity(), number);
        if (info == null) {
            formattedNumber = number;
            nameText = "";
            numberType = 0;
            numberLabel = "";
            photoUri = null;
            lookupUri = null;
        } else {
            formattedNumber = info.phoneNumber;
            nameText = info.name;
            numberType = info.numberType;
            numberLabel = info.phoneLabel;
            photoUri = info.photoUri;
            lookupUri = info.contactContentUri;
        }
        return new PhoneCallDetails(number, formattedNumber, new int[] { callType }, date, duration, accountId,
                statusCode, statusText, nameText, numberType, numberLabel, lookupUri, photoUri);
    } finally {
        if (callCursor != null) {
            callCursor.close();
        }
    }
}

From source file:com.mycompany.popularmovies.DetailActivity.DetailFragment.java

@Override
public void onClick(View v) {
    if (v.getId() == R.id.favorite) {
        Uri uri = MovieContract.MovieTable.CONTENT_URI;
        ContentResolver resolver = mActivity.getContentResolver();
        Cursor favoriteStatusCursor = resolver.query(uri,
                new String[] { MovieContract.MovieTable.COLUMN_FAVORITED },
                MovieContract.MovieTable._ID + "== ?", new String[] { Integer.toString(mMovieId) }, null);
        if (favoriteStatusCursor != null && favoriteStatusCursor.moveToFirst()) {
            Integer favoriteStatus = favoriteStatusCursor
                    .getInt(favoriteStatusCursor.getColumnIndex(MovieContract.MovieTable.COLUMN_FAVORITED));
            Integer flippedFavoriteStatus = favoriteStatus == 0 ? 1 : 0;
            ContentValues updateFavoriteStatusValues = new ContentValues();
            updateFavoriteStatusValues.put(MovieContract.MovieTable.COLUMN_FAVORITED, flippedFavoriteStatus);
            resolver.update(uri, updateFavoriteStatusValues, MovieContract.MovieTable._ID + " == ?",
                    new String[] { Integer.toString(mMovieId) });
            favoriteStatusCursor.close();
        }//from w ww.ja  v a  2  s.  com
    } else if (v.getId() == R.id.trailer_thumbnail) {
        String link = (String) v.getTag();
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link)));
    } else if (v.getId() == R.id.review) {
        final RelativeLayout reviewItem = (RelativeLayout) v;
        final TextView author = (TextView) v.findViewById(R.id.author_full_name);
        final TextView review = (TextView) v.findViewById(R.id.review_text);

        if (reviewItem.getTag() == DetailFragment.TAG_REVIEW_COLLAPSED) {
            author.setVisibility(View.VISIBLE);
            review.setMaxLines(Integer.MAX_VALUE);
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    int excess = mReviewList.getTop() + reviewItem.getBottom()
                            - (mScrollView.getScrollY() + mScrollView.getHeight());
                    if (excess > 0) {
                        if (reviewItem.getHeight() <= mScrollView.getHeight()) {
                            mScrollView.smoothScrollBy(0, excess);
                        } else {
                            mScrollView.smoothScrollTo(0, mReviewList.getTop() + reviewItem.getTop());
                        }
                    }
                }
            });
            reviewItem.setTag(DetailFragment.TAG_REVIEW_EXPANDED);
        } else {
            author.setVisibility(View.GONE);
            review.setMaxLines(REVIEW_MAXLINES);
            reviewItem.setTag(DetailFragment.TAG_REVIEW_COLLAPSED);
        }
    }
}

From source file:com.snda.mymarket.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  .ja v  a2s  .  c  om
 * 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 = new HashSet<Long>(mDownloads.size());
    final ContentResolver resolver = getContentResolver();
    final Cursor cursor = resolver.query(Downloads.ALL_DOWNLOADS_CONTENT_URI, null, null, null, null);
    try {
        final DownloadInfo.Reader reader = new DownloadInfo.Reader(resolver, cursor);
        final int idColumn = cursor.getColumnIndexOrThrow(Downloads._ID);
        while (cursor.moveToNext()) {
            final long id = cursor.getLong(idColumn);
            staleIds.remove(id);
            DownloadInfo info = mDownloads.get(id);
            if (info != null) {
                updateDownload(reader, info, now);
            } else {
                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);
                }
                Helpers.deleteFile(getContentResolver(), info.mId, info.mFileName, info.mMimeType);
            } else {
                // Kick off download task if ready
                final boolean activeDownload = info.startIfReady(this.mNotifier);
                final boolean activeScan = info.startScanIfReady(mScanner);
                if (DEBUG_LIFECYCLE && (activeDownload || activeScan)) {
                    Log.v(Constants.TAG, "Download " + info.mId + ": activeDownload=" + activeDownload
                            + ", activeScan=" + activeScan);
                }
                isActive |= activeDownload;
                isActive |= activeScan;
            }
            // Keep track of nearest next action
            nextActionMillis = Math.min(info.nextActionMillis(now), nextActionMillis);
        }
    } finally {
        cursor.close();
    }
    // Clean up stale downloads that disappeared
    for (Long id : staleIds) {
        deleteDownloadLocked(id);
    }
    // Update notifications visible to user
    mNotifier.updateWith(mDownloads);
    // 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) {
        if (Constants.LOGV) {
            Log.v(Constants.TAG, "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:gov.wa.wsdot.android.wsdot.service.MountainPassesSyncService.java

/** 
 * Check the mountain pass table for any starred entries. If we find some, save them
 * to a list so we can re-star those passes after we flush the database.
 *///from w  w  w . j  a v a 2 s  . c o  m
private List<Integer> getStarred() {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;
    List<Integer> starred = new ArrayList<Integer>();

    try {
        cursor = resolver.query(MountainPasses.CONTENT_URI, new String[] { MountainPasses.MOUNTAIN_PASS_ID },
                MountainPasses.MOUNTAIN_PASS_IS_STARRED + "=?", new String[] { "1" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                starred.add(cursor.getInt(0));
                cursor.moveToNext();
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return starred;
}

From source file:idea.ruan.oksun.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city/*from   ww w  .  j a  va  2 s. co m*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {

    ContentResolver contentResolver = mContext.getContentResolver();

    Uri locationTableUri = WeatherContract.LocationEntry.CONTENT_URI;

    long locationId;
    Cursor c = contentResolver.query(locationTableUri, new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_CITY_NAME + " = ?", new String[] { cityName }, null);
    if (c.moveToFirst()) {

        int i = c.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = c.getLong(i);

    } else {

        ContentValues cv = new ContentValues();

        cv.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        cv.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        cv.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        cv.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        locationId = ContentUris.parseId(contentResolver.insert(locationTableUri, cv));

    }

    c.close();

    return locationId;
}

From source file:com.frostwire.android.gui.Librarian.java

/**
 * @param fileType the file type//  w w w. j a  va 2  s.c  o  m
 * @return the number of files registered in the providers
 */
public int getNumFiles(Context context, byte fileType) {
    TableFetcher fetcher = TableFetchers.getFetcher(fileType);
    Cursor c = null;

    int numFiles = 0;

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

    return numFiles;
}

From source file:com.akop.bach.fragment.xboxlive.MessagesFragment.java

@Override
protected Cursor getIconCursor() {
    if (getActivity() == null)
        return null;

    ContentResolver cr = getActivity().getContentResolver();
    return cr.query(Messages.CONTENT_URI, new String[] { Messages._ID, Messages.GAMERPIC },
            Messages.ACCOUNT_ID + "=" + mAccount.getId(), null, Messages.DEFAULT_SORT_ORDER);
}

From source file:com.andryr.musicplayer.activities.MusicPicker.java

private void getSongList() {
    ContentResolver resolver = getContentResolver();
    Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

    Cursor cursor = resolver.query(musicUri, sProjection, null, null, null);

    if (cursor != null && cursor.moveToFirst()) {
        int idCol = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID);
        if (idCol == -1) {
            idCol = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
        }/*from   w  ww . j  ava2 s  .  co m*/
        int titleCol = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int artistCol = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        int albumCol = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
        int albumIdCol = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
        int trackCol = cursor.getColumnIndex(MediaStore.Audio.Media.TRACK);

        int durationCol = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);

        do {
            long id = cursor.getLong(idCol);
            String title = cursor.getString(titleCol);

            String artist = cursor.getString(artistCol);

            String album = cursor.getString(albumCol);

            long albumId = cursor.getLong(albumIdCol);

            int track = cursor.getInt(trackCol);

            long duration = cursor.getLong(durationCol);

            mSongList.add(new Song(id, title, artist, album, albumId, track, duration));
        } while (cursor.moveToNext());

        Collections.sort(mSongList, new Comparator<Song>() {

            @Override
            public int compare(Song lhs, Song rhs) {
                Collator c = Collator.getInstance(Locale.getDefault());
                c.setStrength(Collator.PRIMARY);
                return c.compare(lhs.getTitle(), rhs.getTitle());
            }
        });

    }
    if (cursor != null) {
        cursor.close();
    }
}

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

/**
 * Look at the groups sync settings and the overall sync preference to determine which
 * feeds to sync and add them to the feedsToSync list.
 *//* ww w. jav a2s  .c o m*/
public static void addContactsFeedsToSync(ContentResolver cr, String account, Collection<String> feedsToSync) {
    boolean shouldSyncEverything = getShouldSyncEverything(cr, account);
    if (shouldSyncEverything) {
        feedsToSync.add(getContactsFeedForAccount(account));
        return;
    }

    Cursor cursor = cr.query(Contacts.Groups.CONTENT_URI, new String[] { Groups._SYNC_ID },
            "_sync_account=? AND should_sync>0", new String[] { account }, null);
    try {
        while (cursor.moveToNext()) {
            feedsToSync.add(getContactsFeedForGroup(account, cursor.getString(0)));
        }
    } finally {
        cursor.close();
    }
}