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.ksk.droidbatterybooster.provider.TimeSchedule.java

/**
 * Return an TimeSchedule object representing the schedule id in the database.
 * Returns null if no schedule exists.//from ww w.  j a v  a 2 s  . c o m
 */
public static TimeSchedule getTimeSchedule(ContentResolver contentResolver, long scheduleId) {
    Cursor cursor = contentResolver.query(ContentUris.withAppendedId(CONTENT_URI, scheduleId), QUERY_COLUMNS,
            null, null, null);
    TimeSchedule schedule = null;
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            schedule = new TimeSchedule(cursor);
        }
        cursor.close();
    }
    return schedule;
}

From source file:org.jsharkey.sky.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.
 *///from  w w w  . ja v  a 2s . c o  m
public static void updateForecasts(Context context, Uri appWidgetUri, int days) throws ForecastParseException {

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

    ContentResolver resolver = context.getContentResolver();

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

    // 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);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Query webservice for this location
    List<Forecast> forecasts = queryLocation(lat, lon, days);

    if (forecasts == null || forecasts.size() == 0) {
        throw new ForecastParseException("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.adjust.sdk.Util.java

protected static String getAttributionId(final Context context) {
    try {//from   w ww.j a  va 2  s . co m
        final ContentResolver contentResolver = context.getContentResolver();
        final Uri uri = Uri.parse("content://com.facebook.katana.provider.AttributionIdProvider");
        final String columnName = "aid";
        final String[] projection = { columnName };
        final Cursor cursor = contentResolver.query(uri, projection, null, null, null);

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

        final String attributionId = cursor.getString(cursor.getColumnIndex(columnName));
        cursor.close();
        return attributionId;
    } catch (Exception e) {
        return null;
    }
}

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

private static boolean isItemUpdated(Uri uri, JSONObject item, ContentResolver resolver, int newMemberType)
        throws JSONException {
    final Cursor cursor = resolver.query(uri, MixItContract.Members.PROJ_DETAIL.PROJECTION, null, null, null);
    try {/* w ww  .j a  v a2  s  . c  o  m*/
        if (!cursor.moveToFirst()) {
            return false;
        }

        String curFirstName = cursor.getString(MixItContract.Members.PROJ_DETAIL.FIRSTNAME);
        if (TextUtils.isEmpty(curFirstName)) {
            curFirstName = EMPTY;
        }
        String curLastName = cursor.getString(MixItContract.Members.PROJ_DETAIL.LASTNAME);
        if (TextUtils.isEmpty(curLastName)) {
            curLastName = EMPTY;
        }

        String curLogin = cursor.getString(MixItContract.Members.PROJ_DETAIL.LOGIN);
        if (TextUtils.isEmpty(curLogin)) {
            curLogin = EMPTY;
        }

        String curCompany = cursor.getString(MixItContract.Members.PROJ_DETAIL.COMPANY);
        if (TextUtils.isEmpty(curCompany)) {
            curCompany = EMPTY;
        }

        String curShortDesc = cursor.getString(MixItContract.Members.PROJ_DETAIL.SHORT_DESC);
        if (TextUtils.isEmpty(curShortDesc)) {
            curShortDesc = EMPTY;
        }

        String curLongDesc = cursor.getString(MixItContract.Members.PROJ_DETAIL.LONG_DESC);
        if (TextUtils.isEmpty(curLongDesc)) {
            curLongDesc = EMPTY;
        }

        String curImageUrl = cursor.getString(MixItContract.Members.PROJ_DETAIL.IMAGE_URL);
        if (TextUtils.isEmpty(curImageUrl)) {
            curImageUrl = EMPTY;
        }

        final int curNbConsults = cursor.getInt(MixItContract.Members.PROJ_DETAIL.NB_CONSULT);

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

        // final int curMemberType = cursor.getInt(MixItContract.Members.PROJ_DETAIL.TYPE);

        final String newFirstName = item.has(TAG_FIRSTNAME) ? item.getString(TAG_FIRSTNAME).trim()
                : curFirstName;
        final String newLastName = item.has(TAG_LASTNAME) ? item.getString(TAG_LASTNAME).trim() : curLastName;
        final String newLogin = item.has(TAG_LOGIN) ? item.getString(TAG_LOGIN).trim() : curLogin;
        final String newCompany = item.has(TAG_COMPANY) ? item.getString(TAG_COMPANY).trim() : curCompany;
        final String newShortDesc = item.has(TAG_SHORT_DESC) ? item.getString(TAG_SHORT_DESC).trim()
                : curShortDesc;
        final String newLongDesc = item.has(TAG_LONG_DESC) ? item.getString(TAG_LONG_DESC).trim() : curLongDesc;
        final String newImageUrl = item.has(TAG_LOGO) ? item.getString(TAG_LOGO).trim()
                : item.has(TAG_IMAGE_URL) ? item.getString(TAG_IMAGE_URL).trim() : curImageUrl;
        final int newNbConsults = item.has(TAG_NB_CONSULTS) ? item.getInt(TAG_NB_CONSULTS) : curNbConsults;
        final String newLevel = item.has(TAG_LEVEL) ? item.getString(TAG_LEVEL).trim() : curLevel;

        return !curFirstName.equalsIgnoreCase(newFirstName) || //
                !curLastName.equalsIgnoreCase(newLastName) || //
                !curLogin.equals(newLogin) || //
                !curCompany.equals(newCompany) || //
                !curShortDesc.equals(newShortDesc) || //
                !curLongDesc.equals(newLongDesc) || //
                !curImageUrl.equals(newImageUrl) || //
                curNbConsults != newNbConsults || //
                !curLevel.equals(newLevel)
        /* || // curMemberType != newMemberType && newMemberType != MixItContract.Members.TYPE_MEMBER */;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

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

/**
 * Method that returns an array with all the unique albums paths and ids.
 *
 * @param cr The ContentResolver/*from w w w. j  ava2 s  . c  o  m*/
 * @return The albums map
 */
public static Map<String, Long> getAllAlbums(ContentResolver cr) {
    final Map<String, Long> albums = new HashMap<>();
    final String[] projection = { "distinct " + MediaStore.Audio.Media.ALBUM_ID,
            "substr(" + MediaStore.Audio.Media.DATA + ", 0, length(" + MediaStore.Audio.Media.DATA
                    + ") - length(" + MediaStore.Audio.Media.DISPLAY_NAME + "))" };
    final String where = MediaStore.Audio.Media.IS_MUSIC + " = ?";
    Cursor c = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, where, new String[] { "1" },
            null);
    if (c != null) {
        try {
            for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
                long albumId = c.getLong(0);
                String albumPath = c.getString(1);
                albums.put(albumPath, albumId);
            }
        } finally {
            IOUtils.closeQuietly(c);
        }
    }
    return albums;
}

From source file:com.cyou.cma.clockscreen.fragment.QuickContactsFragment.java

public static String getPhoneNumber(Context mContext, long sid) {
    // List<ContactBean> contactList = new ArrayList<ContactBean>();
    String[] PHONES_PROJECTION = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER, Phone.CONTACT_ID };
    String selection = null;/*from  w w  w.j  a v  a 2 s  . c o  m*/
    String[] selectionArg = null;
    if (sid > 0) {
        selection = Phone.CONTACT_ID + " = ?";
        selectionArg = new String[] { String.valueOf(sid) };
    }
    ContentResolver resolver = mContext.getContentResolver();
    Cursor phoneCursor = null;
    try {
        phoneCursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, selection, selectionArg, null);

        if (phoneCursor != null) {
            int idIndex = phoneCursor.getColumnIndex(Phone.CONTACT_ID);
            int nameIndex = phoneCursor.getColumnIndex(Phone.DISPLAY_NAME);
            int numberIndex = phoneCursor.getColumnIndex(Phone.NUMBER);
            // ContactBean bean;
            while (phoneCursor.moveToNext()) {
                String phoneNumber = phoneCursor.getString(numberIndex);
                if (TextUtils.isEmpty(phoneNumber))
                    continue;
                phoneNumber = phoneNumber.replaceAll("-", "").replaceAll(" ", "").replaceAll("\\(", "")
                        .replaceAll("\\)", "");
                // bean = new ContactBean();
                // bean.setContact_mobile(phoneNumber);
                // bean.setName(phoneCursor.getString(nameIndex));
                // bean.setSid(phoneCursor.getLong(idIndex));
                // contactList.add(bean);
                return phoneNumber;
            }
            phoneCursor.close();
        }
    } catch (Exception e) {
        if (phoneCursor != null) {
            try {
                phoneCursor.close();
            } catch (Exception e1) {

            }
        }
    } finally {
        phoneCursor.close();
    }
    // return contactList;
    return "";
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

public static List<RawContact> getLocalContacts(Context context, Uri uri) {
    Log.i(TAG, "*** Looking for local contacts");
    List<RawContact> localContacts = new ArrayList<RawContact>();

    final ContentResolver resolver = context.getContentResolver();
    final Cursor c = resolver.query(uri, new String[] { Contacts._ID, RawContacts.SOURCE_ID }, null, null,
            null);/* ww w  .  ja  va  2s. com*/
    try {
        while (c.moveToNext()) {
            final long rawContactId = c.getLong(0);
            final String serverContactId = c.getString(1);
            RawContact rawContact = RawContact.create(rawContactId, serverContactId);
            localContacts.add(rawContact);
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }

    Log.i(TAG, "*** ... found " + localContacts.size());
    return localContacts;
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

private static long lookupProfile(ContentResolver resolver, String userId) {
    long profileId = 0;
    final Cursor c = resolver.query(Data.CONTENT_URI, ProfileQuery.PROJECTION, ProfileQuery.SELECTION,
            new String[] { userId }, null);
    try {/*from   w  ww.j  av a2  s.  co m*/
        if ((c != null) && c.moveToFirst()) {
            profileId = c.getLong(ProfileQuery.COLUMN_ID);
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return profileId;
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

public static int getLocalContactsCount(Context context, Account account) {
    Log.i(TAG, "*** Counting local contacts");

    final Uri uri = RawContacts.CONTENT_URI.buildUpon()
            .appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
            .appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type).build();

    final ContentResolver resolver = context.getContentResolver();
    final Cursor c = resolver.query(uri, new String[] { Contacts._ID, RawContacts.SOURCE_ID }, null, null,
            null);//from w  w w.j a  va  2 s  . co m

    int count = 0;
    try {
        count = c.getCount();
    } catch (Exception e) {
    } finally {
        if (c != null) {
            c.close();
        }
    }

    Log.i(TAG, "*** ... found " + count);
    return count;
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

private static long lookupRawContact(ContentResolver resolver, Account account, String serverContactId) {
    long rawContactId = 0;
    final Cursor c = resolver.query(UserIdQuery.CONTENT_URI, UserIdQuery.PROJECTION, UserIdQuery.SELECTION,
            new String[] { account.name, account.type, serverContactId }, null);
    try {//  www  .j a v a2  s.c  o m
        if ((c != null) && c.moveToFirst()) {
            rawContactId = c.getLong(UserIdQuery.COLUMN_RAW_CONTACT_ID);
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return rawContactId;
}