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.cyanogenmod.eleven.MusicPlaybackService.java

/**
 * @return A card ID used to save and restore playlists, i.e., the queue.
 *//*from ww w  .  j  av a 2s.  c o m*/
private int getCardId() {
    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);
        cursor.close();
        cursor = null;
    }
    return mCardId;
}

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

public static ParcelableUser getUserForConversation(Context context, long accountId, long conversationId) {
    final ContentResolver cr = context.getContentResolver();
    final Expression where = Expression.and(Expression.equals(ConversationEntries.ACCOUNT_ID, accountId),
            Expression.equals(ConversationEntries.CONVERSATION_ID, conversationId));
    final Cursor c = cr.query(ConversationEntries.CONTENT_URI, null, where.getSQL(), null, null);
    try {//w w w .j  a va  2  s .  c o m
        if (c.moveToFirst())
            return ParcelableUser.fromDirectMessageConversationEntry(c);
    } finally {
        c.close();
    }
    return null;
}

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

private void parseGames(XboxLiveAccount account) throws ParserException, IOException {
    long started = System.currentTimeMillis();

    String url = String.format(URL_GAME_LIST, mLocale);
    String page = getResponse(url);

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

    long accountId = account.getId();
    String[] queryParams = new String[1];
    int rowNo = 0;
    boolean changed = false;
    Cursor c;//  www .j av a  2 s .c  o m
    ContentValues cv;
    long updated = System.currentTimeMillis();
    List<ContentValues> newCvs = new ArrayList<ContentValues>(100);
    ContentResolver cr = mContext.getContentResolver();
    List<String> gameIds = new ArrayList<String>(50);

    Matcher m = PATTERN_GAME_ITEM.matcher(page);
    while (m.find()) {
        String content = m.group(1);
        App.logv(" *** found it: " + content);
        Matcher im = PATTERN_GAME_TITLE_ID.matcher(content);
        if (!im.find())
            continue;

        String uid = im.group(1);
        String title = htmlDecode(im.group(2));
        String boxArtUrl = null;
        int gpAcquired = 0;
        int achUnlocked = 0;

        gameIds.add(uid);

        im = PATTERN_GAME_BOX_ART.matcher(content);
        if (im.find())
            boxArtUrl = im.group(1);

        im = PATTERN_GAME_SCORE.matcher(content);
        if (im.find()) {
            try {
                gpAcquired = Integer.parseInt(im.group(1));
            } catch (NumberFormatException e) {
            }
        }

        im = PATTERN_GAME_ACHIEVEMENTS.matcher(content);
        if (im.find()) {
            try {
                achUnlocked = Integer.parseInt(im.group(1));
            } catch (NumberFormatException e) {
            }
        }

        // 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);

        try {
            if (c == null || !c.moveToFirst()) // New game
            {
                cv = new ContentValues(15);
                cv.put(Games.ACCOUNT_ID, accountId);
                cv.put(Games.TITLE, title);
                cv.put(Games.UID, uid);
                cv.put(Games.BOXART_URL, boxArtUrl);
                cv.put(Games.LAST_PLAYED, 0);
                cv.put(Games.LAST_UPDATED, updated);
                cv.put(Games.ACHIEVEMENTS_UNLOCKED, achUnlocked);
                cv.put(Games.ACHIEVEMENTS_TOTAL, achUnlocked);
                cv.put(Games.POINTS_ACQUIRED, gpAcquired);
                cv.put(Games.POINTS_TOTAL, gpAcquired);
                cv.put(Games.GAME_URL, (String) null);
                cv.put(Games.INDEX, rowNo);

                // Games with no achievements do not need achievement refresh
                cv.put(Games.ACHIEVEMENTS_STATUS, 1);

                newCvs.add(cv);
            } else // Existing game
            {
                long gameId = c.getLong(COLUMN_GAME_ID);
                long lastPlayedTicksRec = c.getLong(COLUMN_GAME_LAST_PLAYED_DATE);

                cv = new ContentValues(15);

                boolean refreshAchievements = true;

                if (refreshAchievements) {
                    cv.put(Games.ACHIEVEMENTS_UNLOCKED, achUnlocked);
                    cv.put(Games.ACHIEVEMENTS_TOTAL, achUnlocked);
                    cv.put(Games.POINTS_ACQUIRED, gpAcquired);
                    cv.put(Games.POINTS_TOTAL, gpAcquired);
                    cv.put(Games.ACHIEVEMENTS_STATUS, 1);
                }

                cv.put(Games.BEACON_SET, 0);
                cv.put(Games.BEACON_TEXT, (String) null);
                cv.put(Games.LAST_PLAYED, 0);
                cv.put(Games.INDEX, rowNo);
                cv.put(Games.LAST_UPDATED, updated);
                cr.update(Games.CONTENT_URI, cv, Games._ID + "=" + gameId, null);

                changed = true;
            }
        } finally {
            if (c != null)
                c.close();
        }

        rowNo++;
    }

    // Remove games that are no longer present
    c = cr.query(Games.CONTENT_URI, GAMES_PROJECTION, Games.ACCOUNT_ID + "=" + accountId, null, null);

    if (c != null) {
        while (c.moveToNext()) {
            if (!gameIds.contains(c.getString(COLUMN_GAME_UID))) {
                // Game is no longer in list of played games; remove it
                cr.delete(ContentUris.withAppendedId(Games.CONTENT_URI, c.getLong(COLUMN_GAME_ID)), null, null);
                changed = true;
            }
        }

        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.mozilla.SUTAgentAndroid.service.DoCommand.java

public String changeDir(String newDir) {
    String tmpDir = fixFileName(newDir);
    String sRet = sErrorPrefix + "Couldn't change directory to " + tmpDir;
    int nFiles = 0;

    if (tmpDir.contains("org.mozilla.fennec") || tmpDir.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = Uri/*  w  w w .j  av  a2 s  .  c  om*/
                .parse("content://" + (tmpDir.contains("fennec") ? fenProvider : ffxProvider) + "/dir");

        String[] columns = new String[] { "_id", "isdir", "filename" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                tmpDir, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            nFiles = myCursor.getCount();

            if (nFiles > 0) {
                if (myCursor.moveToPosition(0)) {
                    if (myCursor.getLong(myCursor.getColumnIndex("isdir")) == 1) {
                        currentDir = myCursor.getString(myCursor.getColumnIndex("filename"));
                        sRet = "";
                    }
                }
            } else {
                sRet = sErrorPrefix + tmpDir + " is not a valid directory";
            }
            myCursor.close();
        }
    } else {
        File tmpFile = new java.io.File(tmpDir);

        if (tmpFile.exists()) {
            try {
                if (tmpFile.isDirectory()) {
                    currentDir = tmpFile.getCanonicalPath();
                    sRet = "";
                } else
                    sRet = sErrorPrefix + tmpDir + " is not a valid directory";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String isDirectory(String sDir) {
    String sRet = sErrorPrefix + sDir + " does not exist";
    String tmpDir = fixFileName(sDir);
    int nFiles = 0;

    if (tmpDir.contains("org.mozilla.fennec") || tmpDir.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = Uri//from  ww  w.ja  v  a  2s  .  co m
                .parse("content://" + (tmpDir.contains("fennec") ? fenProvider : ffxProvider) + "/dir");

        String[] columns = new String[] { "_id", "isdir", "filename", "length" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                tmpDir, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            nFiles = myCursor.getCount();

            // If no entries the dir is empty
            if (nFiles > 0) {
                if (myCursor.moveToPosition(0)) {
                    sRet = ((myCursor.getLong(myCursor.getColumnIndex("isdir")) == 1) ? "TRUE" : "FALSE");
                }
            }
            myCursor.close();
        }
    } else {
        File tmpFile = new java.io.File(tmpDir);

        if (tmpFile.exists()) {
            sRet = (tmpFile.isDirectory() ? "TRUE" : "FALSE");
        } else {
            try {
                pProc = Runtime.getRuntime().exec(this.getSuArgs("ls -l " + sDir));
                RedirOutputThread outThrd = new RedirOutputThread(pProc, null);
                outThrd.start();
                outThrd.joinAndStopRedirect(5000);
                sRet = outThrd.strOutput;
                if (!sRet.contains("No such file or directory") && sRet.startsWith("l"))
                    sRet = "FALSE";
            } catch (IOException e) {
                sRet = e.getMessage();
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String PrintFileTimestamp(String sFile) {
    String sRet = "";
    String sTmpFileName = fixFileName(sFile);
    long lModified = -1;

    if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = Uri/*w w  w .  j  av a2s.c  om*/
                .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/dir");

        String[] columns = new String[] { "_id", "isdir", "filename", "length", "ts" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpFileName, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            if (myCursor.getCount() > 0) {
                if (myCursor.moveToPosition(0)) {
                    lModified = myCursor.getLong(myCursor.getColumnIndex("ts"));
                }
            }
            myCursor.close();
        }
    } else {
        File theFile = new File(sTmpFileName);

        if (theFile.exists()) {
            lModified = theFile.lastModified();
        }
    }

    if (lModified != -1) {
        Date dtModified = new Date(lModified);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss:SSS");
        sRet = "Last modified: " + sdf.format(dtModified);
    } else {
        sRet = sErrorPrefix + "[" + sTmpFileName + "] doesn't exist";
    }

    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String IsDirWritable(String sDir) {
    String sTmpDir = fixFileName(sDir);
    String sRet = sErrorPrefix + "[" + sTmpDir + "] is not a directory";

    if (sTmpDir.contains("org.mozilla.fennec") || sTmpDir.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;/*from   w  ww  .  ja  v  a2  s.com*/

        ffxFiles = Uri.parse("content://" + (sTmpDir.contains("fennec") ? fenProvider : ffxProvider) + "/dir");

        String[] columns = new String[] { "_id", "isdir", "filename", "length", "writable" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpDir, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            if (myCursor.getCount() > 0) {
                if (myCursor.moveToPosition(0)) {
                    if (myCursor.getLong(myCursor.getColumnIndex("isdir")) == 1) {
                        sRet = "[" + sTmpDir + "] "
                                + ((myCursor.getLong(myCursor.getColumnIndex("writable")) == 1) ? "is"
                                        : "is not")
                                + " writable";
                    }
                }
            }
        }
    } else {
        File dir = new File(sTmpDir);

        if (dir.isDirectory()) {
            sRet = "[" + sTmpDir + "] " + (dir.canWrite() ? "is" : "is not") + " writable";
        } else {
            sRet = sErrorPrefix + "[" + sTmpDir + "] is not a directory";
        }
    }
    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String PrintDir(String sDir) {
    String sRet = "";
    int nFiles = 0;
    String sTmpDir = fixFileName(sDir);

    if (sTmpDir.contains("org.mozilla.fennec") || sTmpDir.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;// w w  w.ja v a  2 s  .c o  m

        ffxFiles = Uri.parse("content://" + (sTmpDir.contains("fennec") ? fenProvider : ffxProvider) + "/dir");

        String[] columns = new String[] { "_id", "isdir", "filename", "length" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpDir, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            nFiles = myCursor.getCount();

            // If only one entry and the index is -1 this is not a directory
            int nNdx = myCursor.getColumnIndex("_id");
            // If no entries the dir is empty
            if (nFiles == 1) {
                sRet = "<empty>";
            } else {
                // Show the entries
                for (int lcv = 1; lcv < nFiles; lcv++) {
                    if (myCursor.moveToPosition(lcv)) {
                        if ((lcv == 0) && (myCursor.getLong(nNdx) == -1)) {
                            sRet = sErrorPrefix + sTmpDir + " is not a directory";
                        } else {
                            sRet += myCursor.getString(2);
                            if (lcv < (nFiles - 1))
                                sRet += "\n";
                        }
                    }
                }
            }
            myCursor.close();
        }
    } else {
        File dir = new File(sTmpDir);

        if (dir.isDirectory()) {
            File[] files = dir.listFiles();

            if (files != null) {
                if ((nFiles = files.length) > 0) {
                    for (int lcv = 0; lcv < nFiles; lcv++) {
                        sRet += files[lcv].getName();
                        if (lcv < (nFiles - 1)) {
                            sRet += "\n";
                        }
                    }
                } else {
                    sRet = "<empty>";
                }
            }
        } else {
            sRet = sErrorPrefix + sTmpDir + " is not a directory";
        }
    }
    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String Cat(String fileName, OutputStream out) {
    String sTmpFileName = fixFileName(fileName);
    String sRet = sErrorPrefix + "Could not read the file " + sTmpFileName;
    byte[] buffer = new byte[4096];
    int nRead = 0;

    if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;/* w ww  .ja  va2 s  .  co m*/

        ffxFiles = Uri
                .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file");

        String[] columns = new String[] { "_id", "chunk" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpFileName, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            int nBytesRecvd = 0;

            for (int lcv = 0; lcv < nRows; lcv++) {
                if (myCursor.moveToPosition(lcv)) {
                    byte[] buf = myCursor.getBlob(1);
                    if (buf != null) {
                        nBytesRecvd += buf.length;
                        try {
                            out.write(buf);
                            sRet = "";
                        } catch (IOException e) {
                            e.printStackTrace();
                            sRet = sErrorPrefix + "Could not write to out " + sTmpFileName;
                        }
                        buf = null;
                    }
                }
            }
            if (nRows == 0) {
                sRet = "";
            }

            myCursor.close();
        }
    } else {
        try {
            FileInputStream fin = new FileInputStream(sTmpFileName);
            while ((nRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, nRead);
            }
            fin.close();
            out.flush();
            sRet = "";
        } catch (FileNotFoundException e) {
            sRet = sErrorPrefix + sTmpFileName + " No such file or directory";
        } catch (IOException e) {
            sRet = e.toString();
        }
    }
    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String HashFile(String fileName) {
    String sTmpFileName = fixFileName(fileName);
    String sRet = sErrorPrefix + "Couldn't calculate hash for file " + sTmpFileName;
    byte[] buffer = new byte[4096];
    int nRead = 0;
    long lTotalRead = 0;
    MessageDigest digest = null;/*  ww w . j  a va 2 s  .co  m*/

    try {
        digest = java.security.MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;

        ffxFiles = Uri
                .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file");

        String[] columns = new String[] { "_id", "chunk" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpFileName, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            int nBytesRecvd = 0;

            for (int lcv = 0; lcv < nRows; lcv++) {
                if (myCursor.moveToPosition(lcv)) {
                    byte[] buf = myCursor.getBlob(1);
                    if (buf != null) {
                        nBytesRecvd += buf.length;
                        digest.update(buf, 0, buf.length);
                        lTotalRead += nRead;
                        buf = null;
                    }
                }
            }
            myCursor.close();
            byte[] hash = digest.digest();

            sRet = getHex(hash);
        }
    } else {
        try {
            FileInputStream srcFile = new FileInputStream(sTmpFileName);
            while ((nRead = srcFile.read(buffer)) != -1) {
                digest.update(buffer, 0, nRead);
                lTotalRead += nRead;
            }
            srcFile.close();
            byte[] hash = digest.digest();

            sRet = getHex(hash);
        } catch (FileNotFoundException e) {
            sRet += " file not found";
        } catch (IOException e) {
            sRet += " io exception";
            e.printStackTrace();
        }
    }
    return (sRet);
}