Example usage for android.content ContentResolver delete

List of usage examples for android.content ContentResolver delete

Introduction

In this page you can find the example usage for android.content ContentResolver delete.

Prototype

public final int delete(@RequiresPermission.Write @NonNull Uri url, @Nullable String where,
        @Nullable String[] selectionArgs) 

Source Link

Document

Deletes row(s) specified by a content URI.

Usage

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

public String RemoveFile(String fileName) {
    String sTmpFileName = fixFileName(fileName);
    String sRet = sErrorPrefix + "Couldn't delete file " + sTmpFileName;

    if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = Uri/*from   w  w w. ja va 2  s .c o m*/
                .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file");
        if (cr.delete(ffxFiles, sTmpFileName, null) == 1) {
            sRet = "deleted " + sTmpFileName;
        }
    } else {
        File f = new File(sTmpFileName);

        if (f.delete())
            sRet = "deleted " + sTmpFileName;
    }

    return (sRet);
}

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

public String PruneDir(String sDir) {
    String sRet = "";
    int nFiles = 0;
    String sSubDir = null;/*  w w  w  .j  a v a2 s .c  om*/
    String sTmpDir = fixFileName(sDir);

    if (sTmpDir.contains("org.mozilla.fennec") || sTmpDir.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = Uri
                .parse("content://" + (sTmpDir.contains("fennec") ? fenProvider : ffxProvider) + "/dir");
        if (cr.delete(ffxFiles, sTmpDir, null) > 0) {
            sRet = "deleted " + sTmpDir;
        }
    } else {
        File dir = new File(sTmpDir);

        if (dir.isDirectory()) {
            sRet = "Deleting file(s) from " + sTmpDir;

            File[] files = dir.listFiles();
            if (files != null) {
                if ((nFiles = files.length) > 0) {
                    for (int lcv = 0; lcv < nFiles; lcv++) {
                        if (files[lcv].isDirectory()) {
                            sSubDir = files[lcv].getAbsolutePath();
                            sRet += "\n" + PruneDir(sSubDir);
                        } else {
                            if (files[lcv].delete()) {
                                sRet += "\n\tDeleted " + files[lcv].getName();
                            } else {
                                sRet += "\n\tUnable to delete " + files[lcv].getName();
                            }
                        }
                    }
                } else
                    sRet += "\n\t<empty>";
            }

            if (dir.delete()) {
                sRet += "\nDeleting directory " + sTmpDir;
            } else {
                sRet += "\nUnable to delete directory " + sTmpDir;
            }
        } else {
            sRet += sErrorPrefix + sTmpDir + " is not a directory";
        }
    }

    return (sRet);
}

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

@SuppressLint("SimpleDateFormat")
@Override/*from   w ww  .  j  a va  2s.c om*/
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:de.vanita5.twittnuker.util.Utils.java

public static synchronized void cleanDatabasesByItemLimit(final Context context) {
    if (context == null)
        return;//from  ww  w .j  av a  2s.com
    final ContentResolver resolver = context.getContentResolver();
    final int itemLimit = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getInt(KEY_DATABASE_ITEM_LIMIT, DEFAULT_DATABASE_ITEM_LIMIT);

    for (final long account_id : getAccountIds(context)) {
        // Clean statuses.
        for (final Uri uri : STATUSES_URIS) {
            if (CachedStatuses.CONTENT_URI.equals(uri)) {
                continue;
            }
            final String table = getTableNameByUri(uri);
            final Where account_where = new Where(Statuses.ACCOUNT_ID + " = " + account_id);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(Statuses._ID)).from(new Tables(table));
            qb.where(new Where(Statuses.ACCOUNT_ID + " = " + account_id));
            qb.orderBy(new OrderBy(Statuses.STATUS_ID + " DESC"));
            qb.limit(itemLimit);
            final Where where = Where.and(Where.notIn(new Column(Statuses._ID), qb.build()), account_where);
            resolver.delete(uri, where.getSQL(), null);
        }
        for (final Uri uri : DIRECT_MESSAGES_URIS) {
            final String table = getTableNameByUri(uri);
            final Where account_where = new Where(DirectMessages.ACCOUNT_ID + " = " + account_id);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(DirectMessages._ID)).from(new Tables(table));
            qb.where(new Where(DirectMessages.ACCOUNT_ID + " = " + account_id));
            qb.orderBy(new OrderBy(DirectMessages.MESSAGE_ID + " DESC"));
            qb.limit(itemLimit);
            final Where where = Where.and(Where.notIn(new Column(DirectMessages._ID), qb.build()),
                    account_where);
            resolver.delete(uri, where.getSQL(), null);
        }
    }
    // Clean cached values.
    for (final Uri uri : CACHE_URIS) {
        final String table = getTableNameByUri(uri);
        final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
        qb.select(new Column(BaseColumns._ID));
        qb.from(new Tables(table));
        qb.orderBy(new OrderBy(BaseColumns._ID + " DESC"));
        qb.limit(itemLimit * 20);
        final Where where = Where.notIn(new Column(BaseColumns._ID), qb.build());
        resolver.delete(uri, where.getSQL(), null);
    }
}

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

@SuppressLint("DefaultLocale")
@Override/*from   w ww. ja  va2 s  . c  o  m*/
protected void parseTrophies(PsnAccount account, long gameId) throws ParserException, IOException {
    // Find game record in local DB
    ContentResolver cr = mContext.getContentResolver();

    String gameUid = Games.getUid(mContext, gameId);

    String url = String.format(URL_TROPHIES_f, gameUid);
    String page = getResponse(url);

    int index = 0;
    long started = System.currentTimeMillis();

    Matcher trophies = PATTERN_TROPHIES.matcher(page);
    Matcher m;

    List<ContentValues> cvList = new ArrayList<ContentValues>(100);
    while (trophies.find()) {
        boolean trophyUnlocked = "true".equalsIgnoreCase(trophies.group(1));
        String trophyContent = trophies.group(2);

        String iconUrl = null;
        if ((m = PATTERN_TROPHY_ICON.matcher(trophyContent)).find())
            iconUrl = getLargeTrophyIcon(resolveImageUrl(url, m.group(1)));

        String title = mContext.getString(R.string.secret_trophy);
        String description = mContext.getString(R.string.this_is_a_secret_trophy);

        if (!(m = PATTERN_TROPHY_TITLE.matcher(trophyContent)).find())
            continue;

        int type = PSN.TROPHY_SECRET;
        boolean isSecret = false;
        String trophyType = m.group(1).toUpperCase();
        if (trophyType.equals("BRONZE"))
            type = PSN.TROPHY_BRONZE;
        else if (trophyType.equals("SILVER"))
            type = PSN.TROPHY_SILVER;
        else if (trophyType.equals("GOLD"))
            type = PSN.TROPHY_GOLD;
        else if (trophyType.equals("PLATINUM"))
            type = PSN.TROPHY_PLATINUM;
        else if (trophyType.equals("UNKNOWN"))
            isSecret = true;

        if (!isSecret) {
            title = htmlDecode(m.group(2));
            if ((m = PATTERN_TROPHY_DESCRIPTION.matcher(trophyContent)).find())
                description = htmlDecode(m.group(1));
        }

        long earned = 0;
        String earnedText = null;
        if (trophyUnlocked) {
            // No more date info
            earned = System.currentTimeMillis();
            earnedText = mContext.getString(R.string.unlocked);
        }

        ContentValues cv = new ContentValues(20);

        cv.put(Trophies.TITLE, title);
        cv.put(Trophies.DESCRIPTION, description);
        cv.put(Trophies.SORT_ORDER, index);
        cv.put(Trophies.EARNED, earned);
        cv.put(Trophies.EARNED_TEXT, earnedText);
        cv.put(Trophies.ICON_URL, iconUrl);
        cv.put(Trophies.GAME_ID, gameId);
        cv.put(Trophies.IS_SECRET, isSecret ? 1 : 0);
        cv.put(Trophies.TYPE, type);

        cvList.add(cv);
        index++;
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("New trophy parsing", started);

    ContentValues[] cva = new ContentValues[cvList.size()];
    cvList.toArray(cva);

    cr.delete(Trophies.CONTENT_URI, Trophies.GAME_ID + "=" + gameId, null);

    // Bulk-insert new trophies
    cr.bulkInsert(Trophies.CONTENT_URI, cva);
    cr.notifyChange(Trophies.CONTENT_URI, null);

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("New trophy processing", started);

    // Update the game to remove the 'dirty' attribute
    ContentValues cv = new ContentValues(10);
    cv.put(Games.TROPHIES_DIRTY, 0);
    cr.update(Games.CONTENT_URI, cv, Games._ID + "=" + gameId, null);

    cr.notifyChange(ContentUris.withAppendedId(Games.CONTENT_URI, gameId), null);

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

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

public static synchronized void cleanDatabasesByItemLimit(final Context context) {
    if (context == null)
        return;/*from   w  ww  .ja va 2  s. c o  m*/
    final ContentResolver resolver = context.getContentResolver();
    final int itemLimit = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getInt(KEY_DATABASE_ITEM_LIMIT, DEFAULT_DATABASE_ITEM_LIMIT);

    for (final long account_id : getAccountIds(context)) {
        // Clean statuses.
        for (final Uri uri : STATUSES_URIS) {
            if (CachedStatuses.CONTENT_URI.equals(uri)) {
                continue;
            }
            final String table = getTableNameByUri(uri);
            final Expression account_where = new Expression(Statuses.ACCOUNT_ID + " = " + account_id);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(Statuses._ID)).from(new Tables(table));
            qb.where(Expression.equals(Statuses.ACCOUNT_ID, account_id));
            qb.orderBy(new OrderBy(Statuses.STATUS_ID, false));
            qb.limit(itemLimit);
            final Expression where = Expression.and(Expression.notIn(new Column(Statuses._ID), qb.build()),
                    account_where);
            resolver.delete(uri, where.getSQL(), null);
        }
        for (final Uri uri : DIRECT_MESSAGES_URIS) {
            final String table = getTableNameByUri(uri);
            final Expression account_where = new Expression(DirectMessages.ACCOUNT_ID + " = " + account_id);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(DirectMessages._ID)).from(new Tables(table));
            qb.where(Expression.equals(DirectMessages.ACCOUNT_ID, account_id));
            qb.orderBy(new OrderBy(DirectMessages.MESSAGE_ID, false));
            qb.limit(itemLimit);
            final Expression where = Expression
                    .and(Expression.notIn(new Column(DirectMessages._ID), qb.build()), account_where);
            resolver.delete(uri, where.getSQL(), null);
        }
    }
    // Clean cached values.
    for (final Uri uri : CACHE_URIS) {
        final String table = getTableNameByUri(uri);
        if (table == null)
            continue;
        final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
        qb.select(new Column(BaseColumns._ID));
        qb.from(new Tables(table));
        qb.orderBy(new OrderBy(BaseColumns._ID, false));
        qb.limit(itemLimit * 20);
        final Expression where = Expression.notIn(new Column(BaseColumns._ID), qb.build());
        resolver.delete(uri, where.getSQL(), null);
    }
}

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

protected void parseTrophies(PsnAccount account, long gameId) throws ParserException, IOException {
    // Find game record in local DB
    ContentResolver cr = mContext.getContentResolver();

    String gameUid = Games.getUid(mContext, gameId);
    List<NameValuePair> inputs = new ArrayList<NameValuePair>();
    inputs.add(new BasicNameValuePair("sortBy", "id_asc"));
    inputs.add(new BasicNameValuePair("titleId", gameUid));

    String page = getResponse(String.format(URL_TROPHIES, URLEncoder.encode(account.getScreenName(), "UTF-8")),
            inputs, true);//w ww .  jav a2 s .co m

    int index = 0;
    long started = System.currentTimeMillis();

    Matcher achievements = PATTERN_TROPHIES.matcher(page);
    Matcher m;

    List<ContentValues> cvList = new ArrayList<ContentValues>(100);
    while (achievements.find()) {
        String trophyRow = achievements.group(2);

        String title = mContext.getString(R.string.secret_trophy);
        if ((m = PATTERN_TROPHY_TITLE.matcher(trophyRow)).find())
            title = htmlDecode(m.group(1));

        String description = mContext.getString(R.string.this_is_a_secret_trophy);
        if ((m = PATTERN_TROPHY_DESCRIPTION.matcher(trophyRow)).find())
            description = htmlDecode(m.group(1));

        String iconUrl = null;
        if ((m = PATTERN_TROPHY_ICON.matcher(trophyRow)).find())
            iconUrl = getAvatarImage(m.group(1));

        long earned = 0;
        if ((m = PATTERN_TROPHY_EARNED.matcher(trophyRow)).find()) {
            try {
                earned = TROPHY_DATE_FORMAT.parse(m.group(1)).getTime();
            } catch (ParseException e) {
                if (App.getConfig().logToConsole())
                    e.printStackTrace();
            }
        }

        boolean isSecret = false;
        int type = 0;

        if ((m = PATTERN_TROPHY_TYPE.matcher(trophyRow)).find()) {
            String trophyType = m.group(1).toUpperCase();
            if (trophyType.equals("BRONZE"))
                type = PSN.TROPHY_BRONZE;
            else if (trophyType.equals("SILVER"))
                type = PSN.TROPHY_SILVER;
            else if (trophyType.equals("GOLD"))
                type = PSN.TROPHY_GOLD;
            else if (trophyType.equals("PLATINUM"))
                type = PSN.TROPHY_PLATINUM;
            else if (trophyType.equals("HIDDEN"))
                isSecret = true;
        }

        ContentValues cv = new ContentValues(20);

        cv.put(Trophies.TITLE, title);
        cv.put(Trophies.DESCRIPTION, description);
        cv.put(Trophies.SORT_ORDER, index);
        cv.put(Trophies.EARNED, earned);
        cv.put(Trophies.ICON_URL, iconUrl);
        cv.put(Trophies.GAME_ID, gameId);
        cv.put(Trophies.IS_SECRET, isSecret ? 1 : 0);
        cv.put(Trophies.TYPE, type);

        cvList.add(cv);
        index++;
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("New trophy parsing", started);

    ContentValues[] cva = new ContentValues[cvList.size()];
    cvList.toArray(cva);

    cr.delete(Trophies.CONTENT_URI, Trophies.GAME_ID + "=" + gameId, null);

    // Bulk-insert new trophies
    cr.bulkInsert(Trophies.CONTENT_URI, cva);
    cr.notifyChange(Trophies.CONTENT_URI, null);

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("New trophy processing", started);

    // Update the game to remove the 'dirty' attribute
    ContentValues cv = new ContentValues(10);
    cv.put(Games.TROPHIES_DIRTY, 0);
    cr.update(Games.CONTENT_URI, cv, Games._ID + "=" + gameId, null);

    cr.notifyChange(ContentUris.withAppendedId(Games.CONTENT_URI, gameId), null);

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

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;//ww  w. j  a  va 2 s. c o  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:com.akop.bach.parser.XboxLiveParser.java

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

    String token = getVToken(String.format(URL_VTOKEN_MESSAGES, mLocale));

    String url = String.format(URL_JSON_MESSAGE_LIST, mLocale);

    List<NameValuePair> inputs = new ArrayList<NameValuePair>(3);
    addValue(inputs, "__RequestVerificationToken", token);

    String page = getResponse(url, inputs, true);
    JSONObject data = getXboxJsonObject(page);

    if (data == null)
        throw new ParserException(mContext, R.string.error_message_retrieval);

    JSONArray messages = data.optJSONArray("Messages");

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

    long updated = started;
    boolean changed = false;
    String uid;/*  w ww . ja  v a2 s .c  om*/
    ContentResolver cr = mContext.getContentResolver();
    Cursor c;
    ContentValues cv;
    List<ContentValues> newCvs = new ArrayList<ContentValues>();
    final String[] columns = new String[] { Messages._ID, Messages.IS_READ };

    for (int i = 0, n = messages.length(); i < n; i++) {
        JSONObject message = messages.optJSONObject(i);

        if (message == null || (uid = message.optString("Id")) == null)
            continue;

        int isRead = message.optBoolean("HasBeenRead") ? 1 : 0;

        c = cr.query(Messages.CONTENT_URI, columns,
                Messages.ACCOUNT_ID + "=" + account.getId() + " AND " + Messages.UID + "=" + uid, null, null);

        try {
            if (c != null && c.moveToFirst()) {
                String gamerpic = message.optString("GamerPic");

                // Message already in system
                cv = new ContentValues(5);
                cv.put(Messages.IS_READ, isRead);
                cv.put(Messages.DELETE_MARKER, updated);
                cv.put(Messages.GAMERPIC, gamerpic);

                changed = true;
                cr.update(Messages.CONTENT_URI, cv, Messages._ID + "=" + c.getLong(0), null);
            } else {
                long sent = parseTicks(message.optString("SentTime"));

                String body = message.optString("Excerpt", "");
                String sender = message.optString("From", "");
                String gamerpic = message.optString("GamerPic");

                int type = XboxLive.MESSAGE_TEXT;
                if (message.optBoolean("HasImage"))
                    type = XboxLive.MESSAGE_OTHER;
                if (message.optBoolean("HasVoice"))
                    type = XboxLive.MESSAGE_VOICE;

                // New message
                cv = new ContentValues(10);
                cv.put(Messages.ACCOUNT_ID, account.getId());
                cv.put(Messages.SENDER, sender);
                cv.put(Messages.GAMERPIC, gamerpic);
                cv.put(Messages.UID, uid);
                cv.put(Messages.IS_READ, isRead);
                cv.put(Messages.IS_DIRTY, 1);
                cv.put(Messages.TYPE, type);
                cv.put(Messages.SENT, sent);
                cv.put(Messages.DELETE_MARKER, updated);
                cv.put(Messages.BODY, htmlDecode(body));

                newCvs.add(cv);
            }
        } finally {
            if (c != null)
                c.close();
        }
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Message list processing", started);

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

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

        cr.bulkInsert(Messages.CONTENT_URI, cvs);

        if (App.getConfig().logToConsole())
            displayTimeTaken("Message list insertion", started);
    }

    int deleted = cr.delete(Messages.CONTENT_URI,
            Messages.DELETE_MARKER + "!=" + updated + " AND " + Messages.ACCOUNT_ID + "=" + account.getId(),
            null);

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

    if (changed || deleted > 0)
        cr.notifyChange(Messages.CONTENT_URI, null);
}

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

private void parseAchievements(XboxLiveAccount account, long gameId) throws ParserException, IOException {
    // Find game record in local DB
    ContentResolver cr = mContext.getContentResolver();
    String gameUid = Games.getUid(mContext, gameId);

    long updated = System.currentTimeMillis();
    long started = System.currentTimeMillis();

    String pageUrl = String.format(URL_ACHIEVEMENTS, mLocale, gameUid);

    String page = getResponse(pageUrl);

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

    Matcher m;//w  w w. j  a  v a2  s .c  o  m
    if (!(m = PATTERN_ACH_JSON.matcher(page)).find())
        throw new ParserException(mContext, R.string.error_achieves_retrieval);

    JSONObject data = getJSONObject(m.group(1), false);
    JSONArray players = data.optJSONArray("Players");

    if (players.length() < 1)
        throw new ParserException(mContext, R.string.error_achieves_retrieval);

    JSONObject player = players.optJSONObject(0);
    String gamertag = player.optString("Gamertag");

    List<ContentValues> cvList = new ArrayList<ContentValues>(100);

    JSONArray achieves = data.optJSONArray("Achievements");
    for (int i = 0, n = achieves.length(); i < n; i++) {
        JSONObject achieve = achieves.optJSONObject(i);
        if (achieve == null || achieve.optString("Id") == null)
            continue;

        JSONObject progRoot = achieve.optJSONObject("EarnDates");
        if (progRoot == null)
            continue;

        JSONObject prog = progRoot.optJSONObject(gamertag);

        String title;
        String description;
        String tileUrl;

        if (achieve.optBoolean("IsHidden")) {
            title = mContext.getString(R.string.secret_achieve_title);
            description = mContext.getString(R.string.secret_achieve_desc);
            tileUrl = URL_SECRET_ACHIEVE_TILE;
        } else {
            title = achieve.optString("Name");
            description = achieve.optString("Description");
            tileUrl = achieve.optString("TileUrl");
        }

        ContentValues cv = new ContentValues(10);

        // TODO cv.put(Achievements.UID, achieve.optString("Id"));
        cv.put(Achievements.GAME_ID, gameId);
        cv.put(Achievements.TITLE, title);
        cv.put(Achievements.DESCRIPTION, description);
        cv.put(Achievements.ICON_URL, tileUrl);
        cv.put(Achievements.POINTS, achieve.optInt("Score", 0));

        if (prog != null) {
            // Unlocked
            long earnedOn = 0;
            if (!prog.optBoolean("IsOffline"))
                earnedOn = parseTicks(prog.optString("EarnedOn"));

            cv.put(Achievements.ACQUIRED, earnedOn);
            cv.put(Achievements.LOCKED, 0);
        } else {
            // Locked
            cv.put(Achievements.ACQUIRED, 0);
            cv.put(Achievements.LOCKED, 1);
        }

        cvList.add(cv);
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("New achievement parsing", started);

    ContentValues[] cva = new ContentValues[cvList.size()];
    cvList.toArray(cva);

    cr.delete(Achievements.CONTENT_URI, Achievements.GAME_ID + "=" + gameId, null);

    // Bulk-insert new achievements
    cr.bulkInsert(Achievements.CONTENT_URI, cva);

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("New achievement processing", started);

    // Update game stats
    JSONObject game = data.optJSONObject("Game");
    if (game != null) {
        ContentValues cv = new ContentValues(10);

        cv.put(Games.LAST_UPDATED, updated);
        cv.put(Games.ACHIEVEMENTS_STATUS, 0);
        cv.put(Games.ACHIEVEMENTS_TOTAL, game.optInt("PossibleAchievements", 0));
        cv.put(Games.POINTS_TOTAL, game.optInt("PossibleScore", 0));

        JSONObject progRoot = game.optJSONObject("Progress");
        if (progRoot != null) {
            JSONObject progress = game.optJSONObject(gamertag);
            if (progress != null) {
                cv.put(Games.ACHIEVEMENTS_UNLOCKED, progress.optInt("Achievements", 0));
                cv.put(Games.POINTS_ACQUIRED, progress.optInt("Score", 0));
                cv.put(Games.LAST_PLAYED, parseTicks(progress.optString("LastPlayed")));
            }
        }

        // Write changes
        cr.update(Games.CONTENT_URI, cv, Games._ID + "=" + gameId, null);
    }

    cr.notifyChange(Achievements.CONTENT_URI, null);

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