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.bluros.music.MusicService.java

private int getmCardId() {
    final ContentResolver resolver = getContentResolver();
    Cursor cursor = resolver.query(Uri.parse("content://media/external/fs_id"), null, null, null, null);
    int mCardId = -1;
    if (cursor != null && cursor.moveToFirst()) {
        mCardId = cursor.getInt(0);//  www  .j a  va  2  s  .c  o m
        cursor.close();
        cursor = null;
    }
    return mCardId;
}

From source file:net.peterkuterna.android.apps.devoxxsched.io.RemoteScheduleHandler.java

@Override
public ArrayList<ContentProviderOperation> parse(ArrayList<JSONArray> entries, ContentResolver resolver)
        throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final HashMap<String, ContentProviderOperation> blockBatchMap = Maps.newHashMap();
    final HashMap<String, ContentProviderOperation> sessionUpdateBatchMap = Maps.newHashMap();

    int nrEntries = 0;
    for (JSONArray schedules : entries) {
        Log.d(TAG, "Retrieved " + schedules.length() + " schedule entries.");
        nrEntries += schedules.length();

        for (int i = 0; i < schedules.length(); i++) {
            JSONObject schedule = schedules.getJSONObject(i);

            final long startTime = ParserUtils.parseDevoxxTime(schedule.getString("fromTime"));
            final long endTime = ParserUtils.parseDevoxxTime(schedule.getString("toTime"));
            final String kind = schedule.getString("kind");

            final String blockId = Blocks.generateBlockId(kind, startTime, endTime);

            if (!blockBatchMap.containsKey(blockId)) {
                final Uri blockUri = Blocks.buildBlockUri(blockId);

                ContentProviderOperation.Builder builder;
                if (isRowExisting(Blocks.buildBlockUri(blockId), BlocksQuery.PROJECTION, resolver)) {
                    builder = ContentProviderOperation.newUpdate(blockUri);
                } else {
                    builder = ContentProviderOperation.newInsert(Blocks.CONTENT_URI);
                    builder.withValue(Blocks.BLOCK_ID, blockId);
                }//from w ww. j  a va2s.c o  m
                builder.withValue(Blocks.BLOCK_START, startTime);
                builder.withValue(Blocks.BLOCK_END, endTime);

                final String type = schedule.getString("type");
                final String code = schedule.getString("code");

                if (code.startsWith("D10")) {
                    builder.withValue(Blocks.BLOCK_TITLE, type.replaceAll("\\ \\(.*\\)", ""));
                } else {
                    builder.withValue(Blocks.BLOCK_TITLE, schedule.getString("code"));
                }

                builder.withValue(Blocks.BLOCK_TYPE, kind);
                blockBatchMap.put(blockId, builder.build());
            }

            if (schedule.has("presentationUri")) {
                final Uri presentationUri = Uri.parse(schedule.getString("presentationUri"));
                final String sessionId = presentationUri.getLastPathSegment();
                final Uri sessionUri = Sessions.buildSessionUri(sessionId);

                if (isRowExisting(sessionUri, SessionsQuery.PROJECTION, resolver)) {
                    String roomId = null;
                    if (schedule.has("room")) {
                        final String roomName = schedule.getString("room");
                        Cursor cursor = resolver.query(Rooms.buildRoomsWithNameUri(roomName),
                                RoomsQuery.PROJECTION, null, null, null);
                        if (cursor.moveToNext()) {
                            roomId = cursor.getString(RoomsQuery.ROOM_ID);
                        }
                        cursor.close();
                    }
                    final ContentProviderOperation.Builder builder = ContentProviderOperation
                            .newUpdate(sessionUri);
                    builder.withValue(Sessions.BLOCK_ID, blockId);
                    builder.withValue(Sessions.ROOM_ID, roomId);
                    if (schedule.has("note")) {
                        final String note = schedule.getString("note");
                        if (note != null && note.trim().length() > 0) {
                            builder.withValue(Sessions.NOTE, note.trim());
                        }
                    }

                    sessionUpdateBatchMap.put(sessionId, builder.build());
                }
            }
        }
    }

    batch.addAll(blockBatchMap.values());
    batch.addAll(sessionUpdateBatchMap.values());

    if (isRemoteSync() && nrEntries > 0) {
        for (String lostId : getLostIds(blockBatchMap.keySet(), Blocks.CONTENT_URI, BlocksQuery.PROJECTION,
                BlocksQuery.BLOCK_ID, resolver)) {
            if (!lostId.startsWith("lab")) {
                final Uri lostBlockUri = Blocks.buildBlockUri(lostId);
                batch.add(ContentProviderOperation.newDelete(lostBlockUri).build());
            }
        }
        for (String lostId : getLostIds(sessionUpdateBatchMap.keySet(), Sessions.CONTENT_URI,
                SessionsQuery.PROJECTION, SessionsQuery.SESSION_ID, resolver)) {
            Uri deleteUri = Sessions.buildSpeakersDirUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildTagsDirUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildSessionUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
    }

    return batch;
}

From source file:com.av.remusic.service.MediaService.java

private int getmCardId() {
    final ContentResolver resolver = getContentResolver();
    Cursor cursor = resolver.query(Uri.parse("content://media/external/fs_id"), null, null, null, null);
    int mCardId = -1;
    if (cursor != null && cursor.moveToFirst()) {
        mCardId = cursor.getInt(0);//from w  w  w.ja  v  a2s .co  m
        cursor.close();
    }
    return mCardId;
}

From source file:com.lgallardo.qbittorrentclient.RefreshListener.java

public static String getFilePathFromUri(Context c, Uri uri) {
    String filePath = null;//w w  w  . ja v  a 2  s  . c  o m
    if ("content".equals(uri.getScheme())) {
        String[] filePathColumn = { MediaStore.MediaColumns.DATA };
        ContentResolver contentResolver = c.getContentResolver();

        Cursor cursor = contentResolver.query(uri, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);
            cursor.close();
        }
    } else if ("file".equals(uri.getScheme())) {
        filePath = new File(uri.getPath()).getAbsolutePath();
    }
    return filePath;
}

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

protected void parseGames(PsnAccount account) throws ParserException, IOException {
    String page = getResponse(String.format(URL_GAMES, URLEncoder.encode(account.getScreenName(), "UTF-8")),
            true);/*from   w ww  .  j a va 2 s  .c o  m*/

    ContentResolver cr = mContext.getContentResolver();
    boolean changed = false;
    long updated = System.currentTimeMillis();
    Cursor c;
    String title;
    String iconUrl;
    String uid;
    int progress;
    int bronze;
    int silver;
    int gold;
    int platinum;
    String[] queryParams = new String[1];
    final long accountId = account.getId();
    ContentValues cv;
    List<ContentValues> newCvs = new ArrayList<ContentValues>(100);

    long started = System.currentTimeMillis();
    Matcher m;
    Matcher gameMatcher = PATTERN_GAMES.matcher(page);

    for (int rowNo = 1; gameMatcher.find(); rowNo++) {
        String group = gameMatcher.group(1);

        if (!(m = PATTERN_GAME_UID.matcher(group)).find())
            continue;

        uid = m.group(2);

        progress = 0;
        if ((m = PATTERN_GAME_PROGRESS.matcher(group)).find())
            progress = Integer.parseInt(m.group(1));

        bronze = silver = gold = platinum = 0;
        if ((m = PATTERN_GAME_TROPHIES.matcher(group)).find()) {
            bronze = Integer.parseInt(m.group(1));

            if (m.find()) {
                silver = Integer.parseInt(m.group(1));

                if (m.find()) {
                    gold = Integer.parseInt(m.group(1));

                    if (m.find()) {
                        platinum = Integer.parseInt(m.group(1));
                    }
                }
            }
        }

        // Check to see if we already have a record of this game
        queryParams[0] = uid;
        c = cr.query(Games.CONTENT_URI, GAMES_PROJECTION,
                Games.ACCOUNT_ID + "=" + accountId + " AND " + Games.UID + "=?", queryParams, null);

        changed = true;

        try {
            if (c == null || !c.moveToFirst()) // New game
            {
                title = "";
                if ((m = PATTERN_GAME_TITLE.matcher(group)).find())
                    title = htmlDecode(m.group(1));

                iconUrl = null;
                if ((m = PATTERN_GAME_ICON.matcher(group)).find())
                    iconUrl = getAvatarImage(m.group(1));

                cv = new ContentValues(15);

                cv.put(Games.ACCOUNT_ID, accountId);
                cv.put(Games.TITLE, title);
                cv.put(Games.UID, uid);
                cv.put(Games.ICON_URL, iconUrl);
                cv.put(Games.PROGRESS, progress);
                cv.put(Games.SORT_ORDER, rowNo);
                cv.put(Games.UNLOCKED_PLATINUM, platinum);
                cv.put(Games.UNLOCKED_GOLD, gold);
                cv.put(Games.UNLOCKED_SILVER, silver);
                cv.put(Games.UNLOCKED_BRONZE, bronze);
                cv.put(Games.TROPHIES_DIRTY, 1);
                cv.put(Games.LAST_UPDATED, updated);

                newCvs.add(cv);
            } else // Existing game
            {
                boolean isDirty = false;
                long gameId = c.getLong(COLUMN_GAME_ID);

                cv = new ContentValues(15);

                if (c.getInt(COLUMN_GAME_PROGRESS) != progress) {
                    isDirty = true;
                    cv.put(Games.PROGRESS, progress);
                }
                if (c.getInt(COLUMN_GAME_BRONZE) != bronze) {
                    isDirty = true;
                    cv.put(Games.UNLOCKED_BRONZE, bronze);
                }
                if (c.getInt(COLUMN_GAME_SILVER) != silver) {
                    isDirty = true;
                    cv.put(Games.UNLOCKED_SILVER, silver);
                }
                if (c.getInt(COLUMN_GAME_GOLD) != gold) {
                    isDirty = true;
                    cv.put(Games.UNLOCKED_GOLD, gold);
                }
                if (c.getInt(COLUMN_GAME_PLATINUM) != platinum) {
                    isDirty = true;
                    cv.put(Games.UNLOCKED_PLATINUM, platinum);
                }

                if (isDirty)
                    cv.put(Games.TROPHIES_DIRTY, 1);

                cv.put(Games.SORT_ORDER, rowNo);
                cv.put(Games.LAST_UPDATED, updated);

                cr.update(Games.CONTENT_URI, cv, Games._ID + "=" + gameId, null);
            }
        } finally {
            if (c != null)
                c.close();
        }
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Game page processing", started);

    if (newCvs.size() > 0) {
        changed = true;

        ContentValues[] cvs = new ContentValues[newCvs.size()];
        newCvs.toArray(cvs);

        cr.bulkInsert(Games.CONTENT_URI, cvs);

        if (App.getConfig().logToConsole())
            displayTimeTaken("Game page insertion", started);
    }

    account.refresh(Preferences.get(mContext));
    account.setLastGameUpdate(System.currentTimeMillis());
    account.save(Preferences.get(mContext));

    if (changed)
        cr.notifyChange(Games.CONTENT_URI, null);
}

From source file:com.andrew.apolloMod.service.ApolloService.java

/**
 * Opens the specified file and readies it for playback.
 * //w ww.  j a  v  a2  s . c  o  m
 * @param path The full path of the file to be opened.
 */
public boolean open(String path) {
    synchronized (this) {
        if (path == null) {
            return false;
        }

        // if mCursor is null, try to associate path with a database cursor
        if (mCursor == null) {

            ContentResolver resolver = getContentResolver();
            Uri uri;
            String where;
            String selectionArgs[];
            if (path.startsWith("content://media/")) {
                uri = Uri.parse(path);
                where = null;
                selectionArgs = null;
            } else {
                // Remove schema for search in the database
                // Otherwise the file will not found
                String data = path;
                if (data.startsWith("file://")) {
                    data = data.substring(7);
                }
                uri = MediaStore.Audio.Media.getContentUriForPath(path);
                where = MediaColumns.DATA + "=?";
                selectionArgs = new String[] { data };
            }

            try {
                mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
                if (mCursor != null) {
                    if (mCursor.getCount() == 0) {
                        mCursor.close();
                        mCursor = null;
                    } else {
                        mCursor.moveToNext();
                        ensurePlayListCapacity(1);
                        mPlayListLen = 1;
                        mPlayList[0] = mCursor.getLong(IDCOLIDX);
                        mPlayPos = 0;
                    }
                }
            } catch (UnsupportedOperationException ex) {
            }

            updateAlbumBitmap();
        }
        mFileToPlay = path;
        mPlayer.setDataSource(mFileToPlay);
        if (mPlayer.isInitialized()) {
            mOpenFailedCounter = 0;
            return true;
        }
        stop(true);
        return false;
    }
}

From source file:com.andrew.apollo.MusicPlaybackService.java

/**
 * @return A card ID used to save and restore playlists, i.e., the queue.
 *//*  ww  w .  j ava 2 s.co  m*/
private int getCardId() {
    int mCardId = -1;
    try {
        final ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(Uri.parse("content://media/external/fs_id"), null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            mCardId = cursor.getInt(0);
            cursor.close();
        }
    } catch (SecurityException e) {
        e.printStackTrace();
        // it seems that content://media/external/fs_id is not accessible
        // from Android 6.0 in some phones or phone states (who knows)
        // this is an undocumented URI
    }
    return mCardId;
}

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

protected void parseFriends(PsnAccount account) throws ParserException, IOException {
    synchronized (PsnUsParser.class) {
        String url = String.format(URL_FRIENDS, Math.random());
        HttpUriRequest request = new HttpGet(url);

        request.addHeader("Referer", "http://us.playstation.com/myfriends/");
        request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        String page = getResponse(request, null);

        ContentResolver cr = mContext.getContentResolver();
        final long accountId = account.getId();
        ContentValues cv;//from   w  ww . jav  a 2s. co m
        List<ContentValues> newCvs = new ArrayList<ContentValues>(100);

        int rowsInserted = 0;
        int rowsUpdated = 0;
        int rowsDeleted = 0;

        long updated = System.currentTimeMillis();
        long started = updated;
        Matcher gameMatcher = PATTERN_FRIENDS.matcher(page);

        while (gameMatcher.find()) {
            String friendGt = htmlDecode(gameMatcher.group(1));
            GamerProfileInfo gpi;

            try {
                gpi = parseGamerProfile(account, friendGt);
            } catch (IOException e) {
                if (App.getConfig().logToConsole())
                    App.logv("Friend " + friendGt + " threw an IOException");

                // Update the DeleteMarker, so that the GT is not removed

                cv = new ContentValues(15);
                cv.put(Friends.DELETE_MARKER, updated);

                cr.update(Friends.CONTENT_URI, cv,
                        Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?",
                        new String[] { friendGt });

                continue;
            } catch (Exception e) {
                // The rest of the exceptions assume problems with Friend
                // and potentially remove him/her

                if (App.getConfig().logToConsole()) {
                    App.logv("Friend " + friendGt + " threw an Exception");
                    e.printStackTrace();
                }

                continue;
            }

            Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION,
                    Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?",
                    new String[] { friendGt }, null);

            long friendId = -1;

            if (c != null) {
                try {
                    if (c.moveToFirst())
                        friendId = c.getLong(0);
                } finally {
                    c.close();
                }
            }

            cv = new ContentValues(15);

            cv.put(Friends.ONLINE_ID, gpi.OnlineId);
            cv.put(Friends.ICON_URL, gpi.AvatarUrl);
            cv.put(Friends.LEVEL, gpi.Level);
            cv.put(Friends.PROGRESS, gpi.Progress);
            cv.put(Friends.ONLINE_STATUS, gpi.OnlineStatus);
            cv.put(Friends.TROPHIES_PLATINUM, gpi.PlatinumTrophies);
            cv.put(Friends.TROPHIES_GOLD, gpi.GoldTrophies);
            cv.put(Friends.TROPHIES_SILVER, gpi.SilverTrophies);
            cv.put(Friends.TROPHIES_BRONZE, gpi.BronzeTrophies);
            cv.put(Friends.PLAYING, gpi.Playing);
            cv.put(Friends.DELETE_MARKER, updated);
            cv.put(Friends.LAST_UPDATED, updated);

            if (friendId < 0) {
                // New
                cv.put(Friends.ACCOUNT_ID, accountId);

                newCvs.add(cv);
            } else {
                cr.update(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), cv, null, null);

                rowsUpdated++;
            }
        }

        // Remove friends
        rowsDeleted = cr.delete(Friends.CONTENT_URI,
                Friends.ACCOUNT_ID + "=" + accountId + " AND " + Friends.DELETE_MARKER + "!=" + updated, null);

        if (newCvs.size() > 0) {
            ContentValues[] cvs = new ContentValues[newCvs.size()];
            newCvs.toArray(cvs);

            rowsInserted = cr.bulkInsert(Friends.CONTENT_URI, cvs);
        }

        account.refresh(Preferences.get(mContext));
        account.setLastFriendUpdate(System.currentTimeMillis());
        account.save(Preferences.get(mContext));

        cr.notifyChange(Friends.CONTENT_URI, null);

        if (App.getConfig().logToConsole())
            started = displayTimeTaken("Friend page processing [I:" + rowsInserted + ";U:" + rowsUpdated + ";D:"
                    + rowsDeleted + "]", started);
    }
}

From source file:org.getlantern.firetweet.util.Utils.java

public static boolean isFilteringUser(Context context, long userId) {
    final ContentResolver cr = context.getContentResolver();
    final Expression where = Expression.equals(Users.USER_ID, userId);
    final Cursor c = cr.query(Users.CONTENT_URI, new String[0], where.getSQL(), null, null);
    try {//ww  w . j  av a  2 s  . co  m
        return c.getCount() > 0;
    } finally {
        c.close();
    }
}