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.polyvi.xface.extension.messaging.XMessagingExt.java

/**
 * ?//  ww w  . ja  v a 2  s .c  o m
 *
 * @param comparisonMsg
 *            ??
 * @param folderType
 *            
 * @param startIndex
 *            
 * @param endIndex
 *            ?
 * @return ?
 */
private JSONArray findMessages(JSONObject comparisonMsg, String folderType, int startIndex, int endIndex)
        throws JSONException {
    // TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }

    ArrayList<String> projections = new ArrayList<String>();
    projections.add("_id");
    projections.add("subject");
    projections.add("address");
    projections.add("body");
    ArrayList<String> projectionsValue = new ArrayList<String>();
    projectionsValue.add(comparisonMsg.optString("messageId"));
    projectionsValue.add(comparisonMsg.optString("subject"));
    projectionsValue.add(comparisonMsg.optString("destinationAddresses"));
    projectionsValue.add(comparisonMsg.optString("body"));

    StringBuilder selection = XUtils.constructSelectionStatement(projections, projectionsValue);

    int isRead = comparisonMsg.getInt("isRead");
    if (-1 != isRead) {
        if (null == selection) {
            selection = new StringBuilder();
        } else {
            selection.append(" AND ");
        }
        selection.append("read");
        selection.append("=");
        selection.append(isRead);
    }
    String selectionStr = null;
    if (null != selection) {
        selectionStr = selection.toString();
    }

    folderType = folderType.toLowerCase();
    Uri findUri = Uri.withAppendedPath(mSMSContentUri, folderType);
    JSONArray messages = new JSONArray();
    try {
        ContentResolver resolver = mContext.getContentResolver();
        Cursor cursor = resolver.query(findUri, null, selectionStr, null, null);
        if (null == cursor) {
            return messages;
        }
        int count = endIndex - startIndex + 1;
        if (cursor.moveToPosition(startIndex)) {
            do {
                JSONObject message = getMessageFromCursor(cursor);
                messages.put(message);
                count--;
            } while (cursor.moveToNext() && count > 0);
        }
        cursor.close();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return messages;
}

From source file:com.sublimis.urgentcallfilter.Magic.java

private boolean isCallerEligible() {
    boolean retVal = true;

    if (MyPreference.isContactsOnly()) {
        if (!strValidAndNotEmpty(mNumber)) {
            retVal = false;//from  w ww  .  j  av a2s.  c o m
        } else {
            try {
                Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(mNumber));

                if (mContext != null) {
                    ContentResolver contentResolver = mContext.getContentResolver();

                    if (contentResolver != null) {
                        Cursor cur = contentResolver.query(uri, new String[] { PhoneLookup._ID }, null, null,
                                null);

                        if (cur == null || cur.getCount() <= 0) {
                            retVal = false;
                        }

                        if (cur != null) {
                            cur.close();
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    return retVal;
}

From source file:com.google.samples.apps.sergio.service.SessionAlarmService.java

private void scheduleAllStarredSessionFeedbacks() {
    final ContentResolver cr = getContentResolver();
    // TODO: Should we also check that SESSION_IN_MY_SCHEDULE is true?
    final Cursor c = cr.query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI,
            new String[] { ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_END,
                    ScheduleContract.Sessions.SESSION_IN_MY_SCHEDULE, },
            null, null, null);//from   w w w  .  j a  v a 2 s. c om
    if (c == null) {
        return;
    }
    while (c.moveToNext()) {
        final String sessionTitle = c.getString(0);
        final long sessionEnd = c.getLong(1);
        scheduleFeedbackAlarm(sessionEnd, UNDEFINED_ALARM_OFFSET, sessionTitle);
    }
}

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

private void synchronizeLocal() {
    getLoaderManager().restartLoader(0, null, mLoaderCallbacks);

    if (mTitleId >= 0) {
        boolean exists = false;
        boolean isDirty = false;

        ContentResolver cr = getActivity().getContentResolver();
        Cursor cursor = cr.query(Games.CONTENT_URI, new String[] { Games.TITLE, Games.ACHIEVEMENTS_STATUS },
                Games._ID + "=" + mTitleId, null, null);

        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    isDirty = (cursor.getInt(1) != 0);
                    exists = true;//from ww w .ja va 2  s. c o m
                    mGameTitle = cursor.getString(0);
                }
            } finally {
                cursor.close();
            }
        }

        if (isDirty)
            synchronizeWithServer();

        if (!exists)
            mTitleId = -1;
    }

    loadGameDetails();
}

From source file:com.google.samples.apps.iosched.service.SessionAlarmService.java

private void scheduleAllStarredSessionFeedbacks() {
    final ContentResolver cr = getContentResolver();
    Cursor c = null;//from   ww w. jav a2s .c  om
    try {
        c = cr.query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI,
                new String[] { ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_END,
                        ScheduleContract.Sessions.SESSION_IN_MY_SCHEDULE, },
                null, null, null);
        if (c == null) {
            return;
        }
        while (c.moveToNext()) {
            final String sessionTitle = c.getString(0);
            final long sessionEnd = c.getLong(1);
            scheduleFeedbackAlarm(sessionEnd, UNDEFINED_ALARM_OFFSET, sessionTitle);
        }
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:com.google.samples.apps.iosched.service.SessionAlarmService.java

private void scheduleAllStarredBlocks() {
    final ContentResolver cr = getContentResolver();
    Cursor c = null;/* w  w  w . java2  s.  com*/
    try {
        c = cr.query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI,
                new String[] {
                        ScheduleContractHelper.formatQueryDistinctParameter(
                                ScheduleContract.Sessions.SESSION_START),
                        ScheduleContract.Sessions.SESSION_END,
                        ScheduleContract.Sessions.SESSION_IN_MY_SCHEDULE },
                null, null, null);
        if (c == null) {
            return;
        }

        while (c.moveToNext()) {
            final long sessionStart = c.getLong(0);
            final long sessionEnd = c.getLong(1);
            scheduleAlarm(sessionStart, sessionEnd, UNDEFINED_ALARM_OFFSET);
        }
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:com.akop.bach.parser.PsnParser.java

private void parseAccountSummary(PsnAccount account) throws ParserException, IOException {
    ContentValues cv = parseSummaryData(account);
    ContentResolver cr = mContext.getContentResolver();

    long accountId = account.getId();
    boolean newRecord = true;

    long started = System.currentTimeMillis();
    Cursor c = cr.query(Profiles.CONTENT_URI, new String[] { Profiles._ID },
            Profiles.ACCOUNT_ID + "=" + accountId, null, null);

    if (c != null) {
        if (c.moveToFirst())
            newRecord = false;//ww  w  .j  a v  a  2  s  .  c om
        c.close();
    }

    if (newRecord) {
        cv.put(Profiles.ACCOUNT_ID, account.getId());
        cv.put(Profiles.UUID, account.getUuid());

        cr.insert(Profiles.CONTENT_URI, cv);
    } else {
        cr.update(Profiles.CONTENT_URI, cv, Profiles.ACCOUNT_ID + "=" + accountId, null);
    }

    cr.notifyChange(Profiles.CONTENT_URI, null);

    if (App.getConfig().logToConsole())
        displayTimeTaken("Summary update", started);

    account.refresh(Preferences.get(mContext));
    account.setOnlineId(cv.getAsString(Profiles.ONLINE_ID));
    account.setIconUrl(cv.getAsString(Profiles.ICON_URL));
    account.setLastSummaryUpdate(System.currentTimeMillis());
    account.save(Preferences.get(mContext));
}

From source file:com.akop.bach.parser.PsnParser.java

@Override
public void deleteAccount(BasicAccount account) {
    ContentResolver cr = mContext.getContentResolver();
    long accountId = account.getId();

    // Clear games & achievements
    StringBuffer buffer = new StringBuffer();
    Cursor c = cr.query(Games.CONTENT_URI, new String[] { Games._ID }, Games.ACCOUNT_ID + "=" + accountId, null,
            null);//from   w w  w .j  av  a 2  s .  com

    try {
        if (c != null) {
            while (c.moveToNext()) {
                if (buffer.length() > 0)
                    buffer.append(",");
                buffer.append(c.getLong(0));
            }
        }
    } finally {
        if (c != null)
            c.close();
    }

    // Clear trophies
    cr.delete(Trophies.CONTENT_URI, Trophies.GAME_ID + " IN (" + buffer.toString() + ")", null);

    // Clear rest of data
    cr.delete(Games.CONTENT_URI, Games.ACCOUNT_ID + "=" + accountId, null);
    cr.delete(Profiles.CONTENT_URI, Profiles.ACCOUNT_ID + "=" + accountId, null);
    cr.delete(Friends.CONTENT_URI, Friends.ACCOUNT_ID + "=" + accountId, null);

    // Send notifications
    cr.notifyChange(Profiles.CONTENT_URI, null);
    cr.notifyChange(Trophies.CONTENT_URI, null);
    cr.notifyChange(Games.CONTENT_URI, null);
    cr.notifyChange(Friends.CONTENT_URI, null);

    // Delete authenticated session
    deleteSession(account);
}

From source file:gov.wa.wsdot.android.wsdot.service.HighwayAlertsSyncService.java

@SuppressLint("SimpleDateFormat")
@Override// w w  w.j a  v a 2s .  com
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";
    DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy h:mm a");

    /** 
     * Check the cache table for the last time data was downloaded. If we are within
     * the allowed time period, don't sync, otherwise get fresh data from the server.
     */
    try {
        cursor = resolver.query(Caches.CONTENT_URI, projection, Caches.CACHE_TABLE_NAME + " LIKE ?",
                new String[] { "highway_alerts" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS;
            //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min");
            shouldUpdate = (Math.abs(now - lastUpdated) > (5 * DateUtils.MINUTE_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Tapping the refresh button will force a data refresh.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {

        try {
            URL url = new URL(HIGHWAY_ALERTS_URL);
            URLConnection urlConn = url.openConnection();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String jsonFile = "";
            String line;

            while ((line = in.readLine()) != null) {
                jsonFile += line;
            }

            in.close();

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("alerts");
            JSONArray items = result.getJSONArray("items");
            List<ContentValues> alerts = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = items.getJSONObject(j);
                JSONObject startRoadwayLocation = item.getJSONObject("StartRoadwayLocation");
                ContentValues alertData = new ContentValues();

                alertData.put(HighwayAlerts.HIGHWAY_ALERT_ID, item.getString("AlertID"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_HEADLINE, item.getString("HeadlineDescription"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_CATEGORY, item.getString("EventCategory"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_PRIORITY, item.getString("Priority"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_LATITUDE, startRoadwayLocation.getString("Latitude"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_LONGITUDE,
                        startRoadwayLocation.getString("Longitude"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_ROAD_NAME,
                        startRoadwayLocation.getString("RoadName"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_LAST_UPDATED, dateFormat
                        .format(new Date(Long.parseLong(item.getString("LastUpdatedTime").substring(6, 19)))));

                alerts.add(alertData);
            }

            // Purge existing highway alerts covered by incoming data
            resolver.delete(HighwayAlerts.CONTENT_URI, null, null);
            // Bulk insert all the new highway alerts
            resolver.bulkInsert(HighwayAlerts.CONTENT_URI, alerts.toArray(new ContentValues[alerts.size()]));
            // Update the cache table with the time we did the update
            ContentValues values = new ContentValues();
            values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis());
            resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + " LIKE ?",
                    new String[] { "highway_alerts" });

            responseString = "OK";
        } catch (Exception e) {
            Log.e(DEBUG_TAG, "Error: " + e.getMessage());
            responseString = e.getMessage();
        }
    } else {
        responseString = "NOP";
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.HIGHWAY_ALERTS_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);
}

From source file:com.jefftharris.passwdsafe.StorageFileListFragment.java

@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    return new AsyncTaskLoader<Cursor>(getActivity()) {
        /** Handle when the loader is reset */
        @Override// w w  w .ja v  a  2s.c o  m
        protected void onReset() {
            super.onReset();
            onStopLoading();
        }

        /** Handle when the loader is started */
        @Override
        protected void onStartLoading() {
            forceLoad();
        }

        /** Handle when the loader is stopped */
        @Override
        protected void onStopLoading() {
            cancelLoad();
        }

        /** Load the files in the background */
        @Override
        public Cursor loadInBackground() {
            PasswdSafeUtil.dbginfo(TAG, "loadInBackground");
            int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
            ContentResolver cr = getContext().getContentResolver();
            List<Uri> permUris = ApiCompat.getPersistedUriPermissions(cr);
            for (Uri permUri : permUris) {
                PasswdSafeUtil.dbginfo(TAG, "Checking persist perm %s", permUri);
                Cursor cursor = null;
                try {
                    cursor = cr.query(permUri, null, null, null, null);
                    if ((cursor != null) && (cursor.moveToFirst())) {
                        ApiCompat.takePersistableUriPermission(cr, permUri, flags);
                    } else {
                        ApiCompat.releasePersistableUriPermission(cr, permUri, flags);
                        itsRecentFilesDb.removeUri(permUri);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "File remove error: " + permUri, e);
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            }

            try {
                return itsRecentFilesDb.queryFiles();
            } catch (Exception e) {
                Log.e(TAG, "Files load error", e);
            }
            return null;
        }
    };
}