Example usage for android.content ContentResolver notifyChange

List of usage examples for android.content ContentResolver notifyChange

Introduction

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

Prototype

public void notifyChange(@NonNull Uri uri, @Nullable ContentObserver observer) 

Source Link

Document

Notify registered observers that a row was updated and attempt to sync changes to the network.

Usage

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

private void parseFriends(XboxLiveAccount account) throws IOException, ParserException {
    long started = System.currentTimeMillis();
    long updated = System.currentTimeMillis();
    long accountId = account.getId();

    synchronized (XboxLiveParser.class) {
        String token = getVToken(String.format(URL_VTOKEN_FRIENDS, mLocale));

        String url = String.format(URL_JSON_FRIEND_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_friend_retrieval);

        ContentResolver cr = mContext.getContentResolver();
        List<ContentValues> newCvs = new ArrayList<ContentValues>(100);

        parseFriendSection(accountId, data.optJSONArray("Friends"), updated, newCvs, -1);
        parseFriendSection(accountId, data.optJSONArray("Incoming"), updated, newCvs,
                XboxLive.STATUS_INVITE_RCVD);
        parseFriendSection(accountId, data.optJSONArray("Outgoing"), updated, newCvs,
                XboxLive.STATUS_INVITE_SENT);

        // Remove friends that are missing from list
        cr.delete(Friends.CONTENT_URI,
                Friends.DELETE_MARKER + "!=" + updated + " AND " + Friends.ACCOUNT_ID + "=" + accountId, null);

        if (newCvs.size() > 0) {
            ContentValues[] cvs = new ContentValues[newCvs.size()];
            newCvs.toArray(cvs);/*  ww w  .j av a2s . c o  m*/

            cr.bulkInsert(Friends.CONTENT_URI, cvs);

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

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

        // A friend list is very likely to change at every sync, so
        // we just do it no matter what
        cr.notifyChange(Friends.CONTENT_URI, null);
    }

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

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

private ContentValues[] parseGetBeacons(String gamertag, String token) throws IOException, ParserException {
    long started = System.currentTimeMillis();

    ContentResolver cr = mContext.getContentResolver();
    String url = String.format(URL_JSON_BEACONS, mLocale);

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

    if (gamertag != null)
        addValue(inputs, "gamertag", gamertag);

    JSONArray activities = getXboxJsonArray(url, inputs);

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

    List<ContentValues> cvList = new ArrayList<ContentValues>();
    if (activities != null) {
        for (int i = 0, n = activities.length(); i < n; i++) {
            JSONObject activity = activities.optJSONObject(i);
            String titleId;/*from w ww  . j ava 2 s . co  m*/
            JSONObject beacon;

            if (activity == null || (titleId = activity.optString("titleId")) == null
                    || (beacon = activity.optJSONObject("beacon")) == null) {
                continue;
            }

            ContentValues cv = new ContentValues();
            cv.put(Beacons.TITLE_ID, titleId);
            cv.put(Beacons.TITLE_NAME, activity.optString("titleName"));
            cv.put(Beacons.TITLE_BOXART, getBoxArt(titleId, false));
            cv.put(Beacons.TEXT, beacon.isNull("text") ? null : beacon.optString("text"));

            cvList.add(cv);
        }

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

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Beacon data collection", started);

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

    return cvArray;
}

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

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

    ContentResolver cr = mContext.getContentResolver();
    String url = String.format(URL_JSON_BEACONS, mLocale);

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

    JSONArray activities = getXboxJsonArray(url, inputs);

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

    if (activities != null) {
        // Unset all current beacons

        ContentValues cv = new ContentValues();
        cv.put(Games.BEACON_SET, 0);/*from   w w w .  j  a v a2  s  .c o  m*/
        cv.put(Games.BEACON_TEXT, (String) null);

        cr.update(Games.CONTENT_URI, cv, Games.ACCOUNT_ID + "=" + account.getId(), null);

        for (int i = 0, n = activities.length(); i < n; i++) {
            JSONObject activity = activities.optJSONObject(i);
            String titleId;
            JSONObject beacon;

            if (activity == null || (titleId = activity.optString("titleId")) == null
                    || (beacon = activity.optJSONObject("beacon")) == null) {
                continue;
            }

            Long gameId = Games.getId(mContext, account, titleId);
            if (gameId == null)
                continue;

            cv = new ContentValues();
            cv.put(Games.BEACON_SET, 1);
            cv.put(Games.BEACON_TEXT, beacon.optString("text"));

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

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

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Beacon updates", started);
}

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

@SuppressLint("DefaultLocale")
@Override// w w w .java2s .c o  m
protected void parseGames(PsnAccount account) throws ParserException, IOException {
    long started = System.currentTimeMillis();
    boolean keepGoing = true;
    List<ContentValues> cvList = new ArrayList<ContentValues>();

    for (int startIndex = 0; keepGoing; startIndex += 16) {
        String url = String.format(URL_GAMES, startIndex);
        String page = getResponse(url);

        keepGoing = parseGamePage(startIndex, page, cvList);
    }

    final long accountId = account.getId();
    ContentResolver cr = mContext.getContentResolver();
    String[] queryParams = new String[1];
    Cursor c;
    long updated = System.currentTimeMillis();
    List<ContentValues> newCvs = new ArrayList<ContentValues>(100);

    // Check to see if we already have a record of this game
    for (ContentValues cv : cvList) {
        queryParams[0] = cv.getAsString(Games.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.put(Games.ACCOUNT_ID, accountId);
                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);

                if (c.getInt(COLUMN_GAME_PROGRESS) != cv.getAsInteger(Games.PROGRESS))
                    isDirty = true;
                if (c.getInt(COLUMN_GAME_BRONZE) != cv.getAsInteger(Games.UNLOCKED_BRONZE))
                    isDirty = true;
                if (c.getInt(COLUMN_GAME_SILVER) != cv.getAsInteger(Games.UNLOCKED_SILVER))
                    isDirty = true;
                if (c.getInt(COLUMN_GAME_GOLD) != cv.getAsInteger(Games.UNLOCKED_GOLD))
                    isDirty = true;
                if (c.getInt(COLUMN_GAME_PLATINUM) != cv.getAsInteger(Games.UNLOCKED_PLATINUM))
                    isDirty = true;

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

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

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

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

@SuppressLint("DefaultLocale")
@Override/*  w w  w  .j  a  v  a  2s.  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:com.akop.bach.parser.XboxLiveParser.java

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

    // Clear games & achievements
    Cursor c = cr.query(Games.CONTENT_URI, new String[] { Games._ID }, Games.ACCOUNT_ID + "=" + accountId, null,
            null);// w  w w .j av  a2s  .  c  o m

    if (c != null) {
        StringBuffer buffer = new StringBuffer();

        try {
            while (c.moveToNext()) {
                if (buffer.length() > 0)
                    buffer.append(",");
                buffer.append(c.getLong(0));
            }

            if (buffer.length() > 0) {
                // Clear achievements
                cr.delete(Achievements.CONTENT_URI, Achievements.GAME_ID + " IN (" + buffer.toString() + ")",
                        null);
            }
        } catch (Exception e) {
            // Do nothing
        } finally {
            c.close();
        }
    }

    try {
        // Clear games
        cr.delete(Games.CONTENT_URI, Games.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete friends
        cr.delete(Friends.CONTENT_URI, Friends.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete messages
        cr.delete(Messages.CONTENT_URI, Messages.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete sent messages
        cr.delete(SentMessages.CONTENT_URI, SentMessages.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete beacons
        cr.delete(Beacons.CONTENT_URI, Beacons.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete profiles
        cr.delete(Profiles.CONTENT_URI, Profiles.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete notify states
        cr.delete(NotifyStates.CONTENT_URI, Profiles.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete authenticated session
        deleteSession(account);
    } catch (Exception e) {
        // Do nothing
    }

    // Send notifications
    cr.notifyChange(Achievements.CONTENT_URI, null);
    cr.notifyChange(Games.CONTENT_URI, null);
    cr.notifyChange(Friends.CONTENT_URI, null);
    cr.notifyChange(Messages.CONTENT_URI, null);
    cr.notifyChange(Profiles.CONTENT_URI, null);
    cr.notifyChange(Beacons.CONTENT_URI, null);
    cr.notifyChange(SentMessages.CONTENT_URI, null);
    cr.notifyChange(NotifyStates.CONTENT_URI, null);

}

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

@SuppressLint("DefaultLocale")
@Override//  www .  ja  v a  2s . c  om
protected void parseFriendSummary(PsnAccount account, String friendOnlineId)
        throws ParserException, IOException {
    String url = String.format(URL_FRIEND_SUMMARY_f, URLEncoder.encode(friendOnlineId, "UTF-8"));
    String friendData = getResponse(url);

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

    long updated = System.currentTimeMillis();
    long started = updated;
    long friendId = -1;

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

    Matcher m;
    Matcher friendMatcher = PATTERN_FRIEND_SUMMARY.matcher(friendData);
    if (friendMatcher.find() && friendMatcher.find()) // skip the first
    {
        String friendCard = friendMatcher.group(1);

        String onlineId = null;
        if ((m = PATTERN_FRIEND_SUMMARY_ONLINE_ID.matcher(friendCard)).find())
            onlineId = htmlDecode(m.group(1));

        if (onlineId != null) {
            int progress = 0;
            if ((m = PATTERN_FRIEND_SUMMARY_PROGRESS.matcher(friendCard)).find())
                progress = Integer.parseInt(m.group(1));

            int level = 0;
            if ((m = PATTERN_FRIEND_SUMMARY_LEVEL.matcher(friendCard)).find())
                level = Integer.parseInt(m.group(1));

            String iconUrl = null;
            if ((m = PATTERN_FRIEND_SUMMARY_AVATAR.matcher(friendCard)).find())
                iconUrl = getLargeAvatarIcon(resolveImageUrl(url, m.group(1)));

            int memberType = PSN.MEMBER_TYPE_FREE;
            if ((m = PATTERN_FRIEND_SUMMARY_IS_PLUS.matcher(friendCard)).find())
                memberType = PSN.MEMBER_TYPE_PLUS;

            int bronze = 0;
            int silver = 0;
            int gold = 0;
            int platinum = 0;

            m = PATTERN_FRIEND_SUMMARY_TROPHIES.matcher(friendCard);
            while (m.find()) {
                String type = m.group(1).toLowerCase();
                if ("bronze".equals(type))
                    bronze = Integer.parseInt(m.group(2));
                else if ("silver".equals(type))
                    silver = Integer.parseInt(m.group(2));
                else if ("gold".equals(type))
                    gold = Integer.parseInt(m.group(2));
                else if ("platinum".equals(type))
                    platinum = Integer.parseInt(m.group(2));
            }

            ContentValues cv = new ContentValues(15);

            cv.put(Friends.LAST_UPDATED, updated);
            cv.put(Friends.ONLINE_ID, onlineId);
            cv.put(Friends.ICON_URL, iconUrl);
            cv.put(Friends.LEVEL, level);
            cv.put(Friends.PROGRESS, progress);
            cv.put(Friends.TROPHIES_PLATINUM, platinum);
            cv.put(Friends.TROPHIES_GOLD, gold);
            cv.put(Friends.TROPHIES_SILVER, silver);
            cv.put(Friends.TROPHIES_BRONZE, bronze);
            cv.put(Friends.MEMBER_TYPE, memberType);

            if (friendId < 0) {
                // New
                cv.put(Friends.ACCOUNT_ID, account.getId());
                cv.put(Friends.ONLINE_STATUS, PSN.STATUS_OTHER);
                cv.put(Friends.PLAYING, (String) null);

                cr.insert(Friends.CONTENT_URI, cv);
            } else {
                // Existing
                cr.update(Friends.CONTENT_URI, cv, Friends._ID + "=" + friendId, null);
            }

            cr.notifyChange(Friends.CONTENT_URI, null);
        }
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("parseCompareGames/processing", started);
}

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);//from  w w w.  j  a  v  a2  s. c om

    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;/*from   w ww .  j av  a 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  w  w .j a v  a  2 s .co  m
    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);
}