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.oliversride.wordryo.Utils.java

public static String phoneToContact(Context context, String phone, boolean phoneStandsIn) {
    // I'm assuming that since context is passed this needn't
    // worry about synchronization -- will always be called from
    // UI thread.
    String name;// ww  w .  ja v a 2s. c  om
    synchronized (s_phonesHash) {
        if (s_phonesHash.containsKey(phone)) {
            name = s_phonesHash.get(phone);
        } else {
            name = null;
            ContentResolver contentResolver = context.getContentResolver();
            Cursor cursor = contentResolver.query(
                    Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone)),
                    new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
            if (cursor.moveToNext()) {
                int indx = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
                name = cursor.getString(indx);
            }
            cursor.close();

            s_phonesHash.put(phone, name);
        }
    }
    if (null == name && phoneStandsIn) {
        name = phone;
    }
    return name;
}

From source file:info.guardianproject.otr.app.im.app.DatabaseUtils.java

public static Cursor queryAccountsForProvider(ContentResolver cr, String[] projection, long providerId) {
    StringBuilder where = new StringBuilder(Imps.Account.ACTIVE);
    where.append("=1 AND ").append(Imps.Account.PROVIDER).append('=').append(providerId);
    Cursor c = cr.query(Imps.Account.CONTENT_URI, projection, where.toString(), null, null);
    if (c != null && !c.moveToFirst()) {
        c.close();/*from w ww.j  av a  2s.  com*/
        return null;
    }
    return c;
}

From source file:fr.mixit.android.io.JsonHandlerApplyTalks.java

private static boolean isItemUpdated(Uri uri, JSONObject item, ContentResolver resolver) throws JSONException {
    final Cursor cursor = resolver.query(uri, MixItContract.Sessions.PROJ_DETAIL.PROJECTION, null, null, null);
    try {/* www.j  a v  a 2 s . co m*/
        if (!cursor.moveToFirst()) {
            return false;
        }

        String curTitle = cursor.getString(MixItContract.Sessions.PROJ_DETAIL.TITLE);
        if (TextUtils.isEmpty(curTitle)) {
            curTitle = EMPTY;
        }

        String curSummary = cursor.getString(MixItContract.Sessions.PROJ_DETAIL.SUMMARY);
        if (TextUtils.isEmpty(curSummary)) {
            curSummary = EMPTY;
        }

        String curDesc = cursor.getString(MixItContract.Sessions.PROJ_DETAIL.DESC);
        if (TextUtils.isEmpty(curDesc)) {
            curDesc = EMPTY;
        }

        final long curStart = cursor.getLong(MixItContract.Sessions.PROJ_DETAIL.START);
        final long curEnd = cursor.getLong(MixItContract.Sessions.PROJ_DETAIL.END);

        String curRoomId = cursor.getString(MixItContract.Sessions.PROJ_DETAIL.ROOM_ID);
        if (TextUtils.isEmpty(curRoomId)) {
            curRoomId = EMPTY;
        }

        final int curNbVotes = cursor.getInt(MixItContract.Sessions.PROJ_DETAIL.NB_VOTES);
        // final int curMyVote = cursor.getInt(MixItContract.Sessions.PROJ_DETAIL.MY_VOTE);
        // final int curIsFavorite = cursor.getInt(MixItContract.Sessions.PROJ_DETAIL.IS_FAVORITE);

        String curFormat = cursor.getString(MixItContract.Sessions.PROJ_DETAIL.FORMAT);
        if (TextUtils.isEmpty(curFormat)) {
            curFormat = EMPTY;
        }

        String curLevel = cursor.getString(MixItContract.Sessions.PROJ_DETAIL.LEVEL);
        if (TextUtils.isEmpty(curLevel)) {
            curLevel = EMPTY;
        }

        String curLang = cursor.getString(MixItContract.Sessions.PROJ_DETAIL.LANG);
        if (TextUtils.isEmpty(curLang)) {
            curLang = EMPTY;
        }

        final String newTitle = item.has(TAG_TITLE) ? item.getString(TAG_TITLE).trim() : curTitle;
        final String newSummary = item.has(TAG_SUMMARY) ? item.getString(TAG_SUMMARY).trim() : curSummary;
        final String newDesc = item.has(TAG_DESC) ? item.getString(TAG_DESC).trim() : curDesc;
        long newStart = 0;
        if (item.has(TAG_START)) {
            final String start = item.getString(TAG_START);
            newStart = DateUtils.parseISO8601(start);
        } else {
            newStart = curStart;
        }
        long newEnd = 0;
        if (item.has(TAG_END)) {
            final String end = item.getString(TAG_END);
            newEnd = DateUtils.parseISO8601(end);
        } else {
            newEnd = curEnd;
        }
        final String newRoomId = item.has(TAG_ROOM) ? item.getString(TAG_ROOM).trim() : curRoomId;
        final int newNbVotes = item.has(TAG_NB_VOTES) ? item.getInt(TAG_NB_VOTES) : curNbVotes;
        // final int newMyVote = session.has(TAG_MY_VOTE) ? session.getBoolean(TAG_MY_VOTE) ? 1 : 0 : curMyVote;
        // final int newIsFavorite = session.has(TAG_IS_FAVORITE) ? session.getInt(TAG_IS_FAVORITE) : curIsFavorite;
        final String newFormat = item.has(TAG_FORMAT) ? item.getString(TAG_FORMAT).trim() : curFormat;
        final String newLevel = item.has(TAG_LEVEL) ? item.getString(TAG_LEVEL).trim() : curLevel;
        final String newLang = item.has(TAG_LANG) ? item.getString(TAG_LANG).trim() : curLang;

        return !curTitle.equals(newTitle) || //
                !curSummary.equals(newSummary) || //
                !curDesc.equals(newDesc) || //
                curStart != newStart || //
                curEnd != newEnd || //
                !curRoomId.equals(newRoomId) || //
                curNbVotes != newNbVotes || //
                // curMyVote != newMyVote ||
                // curIsFavorite != newIsFavorite || //
                !curFormat.equals(newFormat) || //
                !curLevel.equals(newLevel) || //
                !curLang.equals(newLang);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:org.jsharkey.sky.webservice.WebserviceHelper.java

/**
 * Perform a webservice query to retrieve and store the forecast for the
 * given widget. This call blocks until request is finished and
 * {@link Forecasts#CONTENT_URI} has been updated.
 *//* w  w w.jav  a  2 s  .  c o  m*/
public static void updateForecasts(Context context, Uri appWidgetUri, int days) throws ParseException {

    if (sUserAgent == null) {
        prepareUserAgent(context);
    }

    Uri appWidgetForecasts = Uri.withAppendedPath(appWidgetUri, AppWidgets.TWIG_FORECASTS);

    ContentResolver resolver = context.getContentResolver();

    Cursor cursor = null;
    double lat = Double.NaN;
    double lon = Double.NaN;
    String countryCode = null;

    // Pull exact forecast location from database
    try {
        cursor = resolver.query(appWidgetUri, PROJECTION_APPWIDGET, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            lat = cursor.getDouble(COL_LAT);
            lon = cursor.getDouble(COL_LON);
            countryCode = cursor.getString(COL_COUNTRY_CODE);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    Log.d(TAG, "using country code=" + countryCode);

    // Query webservice for this location
    List<Forecast> forecasts = null;
    if (COUNTRY_US.equals(countryCode)) {
        forecasts = new NoaaSource().getForecasts(lat, lon, days);
    } else {
        forecasts = new MetarSource().getForecasts(lat, lon, days);
    }

    if (forecasts == null || forecasts.size() == 0) {
        throw new ParseException("No forecasts found from webservice query");
    }

    // Purge existing forecasts covered by incoming data, and anything
    // before today
    long lastMidnight = ForecastUtils.getLastMidnight();
    long earliest = Long.MAX_VALUE;
    for (Forecast forecast : forecasts) {
        earliest = Math.min(earliest, forecast.validStart);
    }

    resolver.delete(appWidgetForecasts, ForecastsColumns.VALID_START + " >= " + earliest + " OR "
            + ForecastsColumns.VALID_START + " <= " + lastMidnight, null);

    // Insert any new forecasts found
    ContentValues values = new ContentValues();
    for (Forecast forecast : forecasts) {
        Log.d(TAG, "inserting forecast with validStart=" + forecast.validStart);
        values.clear();
        values.put(ForecastsColumns.VALID_START, forecast.validStart);
        values.put(ForecastsColumns.TEMP_HIGH, forecast.tempHigh);
        values.put(ForecastsColumns.TEMP_LOW, forecast.tempLow);
        values.put(ForecastsColumns.CONDITIONS, forecast.conditions);
        values.put(ForecastsColumns.URL, forecast.url);
        if (forecast.alert) {
            values.put(ForecastsColumns.ALERT, ForecastsColumns.ALERT_TRUE);
        }
        resolver.insert(appWidgetForecasts, values);
    }

    // Mark widget cache as being updated
    values.clear();
    values.put(AppWidgetsColumns.LAST_UPDATED, System.currentTimeMillis());
    resolver.update(appWidgetUri, values, null, null);
}

From source file:com.cyanogenmod.filemanager.util.MediaHelper.java

/**
 * Method that converts a file reference to a content uri reference
 *
 * @param cr A content resolver//from   w w w.j a va 2  s.  co  m
 * @param path The path to search
 * @param volume The volume
 * @return Uri The content uri or null if file not exists in the media database
 */
private static Uri fileToContentUri(ContentResolver cr, String path, String volume) {
    final String[] projection = { BaseColumns._ID, MediaStore.Files.FileColumns.MEDIA_TYPE };
    final String where = MediaColumns.DATA + " = ?";
    Uri baseUri = MediaStore.Files.getContentUri(volume);
    Cursor c = cr.query(baseUri, projection, where, new String[] { path }, null);
    try {
        if (c != null && c.moveToNext()) {
            int type = c.getInt(c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MEDIA_TYPE));
            if (type != 0) {
                // Do not force to use content uri for no media files
                long id = c.getLong(c.getColumnIndexOrThrow(BaseColumns._ID));
                return Uri.withAppendedPath(baseUri, String.valueOf(id));
            }
        }
    } finally {
        IOUtils.closeQuietly(c);
    }
    return null;
}

From source file:com.silentcorp.autotracker.db.VehicleDB.java

/**
 * Read a vehicle from the DB given its ID
 * //from   w  w w  .  ja  v  a  2  s.co m
 * @param contentResolver content resolver
 * @param id vehicle ID
 * @param vehicle object to fill, if NULL, new created and returned
 * @return full vehicle object
 * @throws SQLException
 */
public static VehicleBean readVehicle(Context context, long id, VehicleBean vehicle) throws SQLException {
    Uri uri = Uri.parse(DBContentProvider.VEHICLES_URI + "/" + id);
    // Read all columns for the record
    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor = contentResolver.query(uri, null, null, null, null);
    if (cursor == null || cursor.getCount() == 0) {
        throw new SQLException("Unable to find vehicle with ID: " + id + " Corrupt DB?");
    }
    // more then one vehicle
    if (cursor.getCount() > 1) {
        throw new SQLException("More then one vehicle with ID: " + id + " Corrupt DB?");
    }

    cursor.moveToFirst();

    if (vehicle == null) {
        vehicle = new VehicleBean();
    }

    vehicle.setId(id);
    vehicle.setName(Utils.readString(cursor, COL_NAME, TABLE_VEHICLE));
    vehicle.setColor(Utils.readInt(cursor, COL_COLOR, TABLE_VEHICLE));
    vehicle.setMake(Utils.readString(cursor, COL_MAKE, TABLE_VEHICLE));
    vehicle.setModel(Utils.readString(cursor, COL_MODEL, TABLE_VEHICLE));
    vehicle.setYear(Utils.readWhole(cursor, COL_YEAR, TABLE_VEHICLE));
    vehicle.setLicensePlate(Utils.readString(cursor, COL_LICENSE_PLATE, TABLE_VEHICLE));
    vehicle.setPrimaryFuel(Utils.readString(cursor, COL_PRIMARY_FUEL, TABLE_VEHICLE));
    vehicle.setSecondaryFuel(Utils.readString(cursor, COL_SECONDARY_FUEL, TABLE_VEHICLE));
    vehicle.setPurchaseDate(Utils.readLong(cursor, COL_PURCHASE_DATE, TABLE_VEHICLE));
    vehicle.setPurchasePrice(Utils.readDouble(cursor, COL_PURCHASE_PRICE, TABLE_VEHICLE));
    vehicle.setPurchaseOdometer(Utils.readWhole(cursor, COL_PURCHASE_ODOMETER, TABLE_VEHICLE));
    vehicle.setPurchaseNote(Utils.readString(cursor, COL_PURCHASE_NOTE, TABLE_VEHICLE));
    vehicle.setIsSold(Utils.readBoolean(cursor, COL_SELL_FLAG, TABLE_VEHICLE));
    vehicle.setSellDate(Utils.readLong(cursor, COL_SELL_DATE, TABLE_VEHICLE));
    vehicle.setSellPrice(Utils.readDouble(cursor, COL_SELL_PRICE, TABLE_VEHICLE));
    vehicle.setSellOdometer(Utils.readWhole(cursor, COL_SELL_ODOMETER, TABLE_VEHICLE));
    vehicle.setSellNote(Utils.readString(cursor, COL_SELL_NOTE, TABLE_VEHICLE));

    cursor.close();

    return vehicle;
}

From source file:Main.java

@Nullable
public static File getFromMediaUri(Context context, ContentResolver resolver, Uri uri) {
    if (uri == null)
        return null;

    if (SCHEME_FILE.equals(uri.getScheme())) {
        return new File(uri.getPath());
    } else if (SCHEME_CONTENT.equals(uri.getScheme())) {
        final String[] filePathColumn = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME };
        Cursor cursor = null;// w w w. j a v a 2s. c o  m
        try {
            cursor = resolver.query(uri, filePathColumn, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int columnIndex = (uri.toString().startsWith("content://com.google.android.gallery3d"))
                        ? cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
                        : cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
                // Picasa images on API 13+
                if (columnIndex != -1) {
                    String filePath = cursor.getString(columnIndex);
                    if (!TextUtils.isEmpty(filePath)) {
                        return new File(filePath);
                    }
                }
            }
        } catch (IllegalArgumentException e) {
            // Google Drive images
            return getFromMediaUriPfd(context, resolver, uri);
        } catch (SecurityException ignored) {
            // Nothing we can do
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }
    return null;
}

From source file:info.guardianproject.otr.app.im.app.DatabaseUtils.java

public static RoundedAvatarDrawable getAvatarFromAddress(ContentResolver cr, String address, int width,
        int height) throws DecoderException {

    String[] projection = { Imps.Contacts.AVATAR_DATA };
    String[] args = { address };//from  w w  w .  ja va  2 s. c  o m
    String query = Imps.Contacts.USERNAME + " LIKE ?";
    Cursor cursor = cr.query(Imps.Contacts.CONTENT_URI, projection, query, args,
            Imps.Contacts.DEFAULT_SORT_ORDER);

    if (cursor.moveToFirst()) {
        String hexData = cursor.getString(0);
        cursor.close();
        if (hexData.equals("NULL")) {
            return null;
        }

        byte[] data = Hex.decodeHex(hexData.substring(2, hexData.length() - 1).toCharArray());

        return decodeAvatar(data, width, height);
    } else {

        cursor.close();
        return null;
    }
}

From source file:com.smarthome.deskclock.Alarms.java

private static Cursor getFilteredAlarmsCursor(ContentResolver contentResolver) {
    return contentResolver.query(Alarm.Columns.CONTENT_URI, Alarm.Columns.ALARM_QUERY_COLUMNS,
            Alarm.Columns.WHERE_ENABLED, null, null);
}

From source file:com.smarthome.deskclock.Alarms.java

/**
 * Queries all alarms/*from   www .  j  a va2  s  .c om*/
 * @return cursor over all alarms
 */
public static Cursor getAlarmsCursor(ContentResolver contentResolver) {
    return contentResolver.query(Alarm.Columns.CONTENT_URI, Alarm.Columns.ALARM_QUERY_COLUMNS, null, null,
            Alarm.Columns.DEFAULT_SORT_ORDER);
}