Example usage for android.content ContentResolver bulkInsert

List of usage examples for android.content ContentResolver bulkInsert

Introduction

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

Prototype

public final int bulkInsert(@RequiresPermission.Write @NonNull Uri url, @NonNull ContentValues[] values) 

Source Link

Document

Inserts multiple rows into a table at the given URL.

Usage

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   ww  w .j a  va  2 s  .com*/
        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 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  ww.  j a va 2s. c  om
    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);
}

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);/* w  ww . ja  va 2s  .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.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;//from w  w  w .  j  av a2  s  .com
    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:gov.wa.wsdot.android.wsdot.service.MountainPassesSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;/*from  w  w w .  j a va 2s  .co m*/
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";

    /** 
     * 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, new String[] { Caches.CACHE_LAST_UPDATED },
                Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "mountain_passes" }, 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) > (15 * DateUtils.MINUTE_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Ability to force a refresh of camera data.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {
        List<Integer> starred = new ArrayList<Integer>();

        starred = getStarred();
        buildWeatherPhrases();

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

            BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
            GZIPInputStream gzin = new GZIPInputStream(bis);
            InputStreamReader is = new InputStreamReader(gzin);
            BufferedReader in = new BufferedReader(is);

            String mDateUpdated = "";
            String jsonFile = "";
            String line;
            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("GetMountainPassConditionsResult");
            JSONArray passConditions = result.getJSONArray("PassCondition");
            String weatherCondition;
            Integer weather_image;
            Integer forecast_weather_image;
            List<ContentValues> passes = new ArrayList<ContentValues>();

            int numConditions = passConditions.length();
            for (int j = 0; j < numConditions; j++) {
                JSONObject pass = passConditions.getJSONObject(j);
                ContentValues passData = new ContentValues();
                weatherCondition = pass.getString("WeatherCondition");
                weather_image = getWeatherImage(weatherPhrases, weatherCondition);

                String tempDate = pass.getString("DateUpdated");

                try {
                    tempDate = tempDate.replace("[", "");
                    tempDate = tempDate.replace("]", "");

                    String[] a = tempDate.split(",");
                    StringBuilder sb = new StringBuilder();
                    for (int m = 0; m < 5; m++) {
                        sb.append(a[m]);
                        sb.append(",");
                    }
                    tempDate = sb.toString().trim();
                    tempDate = tempDate.substring(0, tempDate.length() - 1);
                    Date date = parseDateFormat.parse(tempDate);
                    mDateUpdated = displayDateFormat.format(date);
                } catch (Exception e) {
                    Log.e(DEBUG_TAG, "Error parsing date: " + tempDate, e);
                    mDateUpdated = "N/A";
                }

                JSONArray forecasts = pass.getJSONArray("Forecast");
                JSONArray forecastItems = new JSONArray();

                int numForecasts = forecasts.length();
                for (int l = 0; l < numForecasts; l++) {
                    JSONObject forecast = forecasts.getJSONObject(l);

                    if (isNight(forecast.getString("Day"))) {
                        forecast_weather_image = getWeatherImage(weatherPhrasesNight,
                                forecast.getString("ForecastText"));
                    } else {
                        forecast_weather_image = getWeatherImage(weatherPhrases,
                                forecast.getString("ForecastText"));
                    }

                    forecast.put("weather_icon", forecast_weather_image);

                    if (l == 0) {
                        if (weatherCondition.equals("")) {
                            weatherCondition = forecast.getString("ForecastText").split("\\.")[0] + ".";
                            weather_image = forecast_weather_image;
                        }
                    }

                    forecastItems.put(forecast);
                }

                passData.put(MountainPasses.MOUNTAIN_PASS_ID, pass.getString("MountainPassId"));
                passData.put(MountainPasses.MOUNTAIN_PASS_NAME, pass.getString("MountainPassName"));
                passData.put(MountainPasses.MOUNTAIN_PASS_WEATHER_ICON, weather_image);
                passData.put(MountainPasses.MOUNTAIN_PASS_FORECAST, forecastItems.toString());
                passData.put(MountainPasses.MOUNTAIN_PASS_WEATHER_CONDITION, weatherCondition);
                passData.put(MountainPasses.MOUNTAIN_PASS_DATE_UPDATED, mDateUpdated);
                passData.put(MountainPasses.MOUNTAIN_PASS_CAMERA, pass.getString("Cameras"));
                passData.put(MountainPasses.MOUNTAIN_PASS_ELEVATION, pass.getString("ElevationInFeet"));
                passData.put(MountainPasses.MOUNTAIN_PASS_TRAVEL_ADVISORY_ACTIVE,
                        pass.getString("TravelAdvisoryActive"));
                passData.put(MountainPasses.MOUNTAIN_PASS_ROAD_CONDITION, pass.getString("RoadCondition"));
                passData.put(MountainPasses.MOUNTAIN_PASS_TEMPERATURE,
                        pass.getString("TemperatureInFahrenheit"));
                JSONObject restrictionOne = pass.getJSONObject("RestrictionOne");
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_ONE,
                        restrictionOne.getString("RestrictionText"));
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_ONE_DIRECTION,
                        restrictionOne.getString("TravelDirection"));
                JSONObject restrictionTwo = pass.getJSONObject("RestrictionTwo");
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_TWO,
                        restrictionTwo.getString("RestrictionText"));
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_TWO_DIRECTION,
                        restrictionTwo.getString("TravelDirection"));

                if (starred.contains(Integer.parseInt(pass.getString("MountainPassId")))) {
                    passData.put(MountainPasses.MOUNTAIN_PASS_IS_STARRED, 1);
                }

                passes.add(passData);

            }

            // Purge existing mountain passes covered by incoming data
            resolver.delete(MountainPasses.CONTENT_URI, null, null);
            // Bulk insert all the new mountain passes
            resolver.bulkInsert(MountainPasses.CONTENT_URI, passes.toArray(new ContentValues[passes.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 + "=?",
                    new String[] { "mountain_passes" });

            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.MOUNTAIN_PASSES_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);
}

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

@SuppressLint("DefaultLocale")
@Override/*  w w  w  . j a  v a 2s.  com*/
protected void parseFriends(PsnAccount account) throws ParserException, IOException {
    synchronized (PsnEuParser.class) {
        ContentResolver cr = mContext.getContentResolver();
        ContentValues cv;
        List<ContentValues> newCvs = new ArrayList<ContentValues>(100);
        final long accountId = account.getId();

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

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

        // Handle pending requests
        String page = getResponse(URL_FRIENDS);

        Matcher m;
        Matcher friendMatcher = PATTERN_FRIENDS_PENDING.matcher(page);

        while (friendMatcher.find()) {
            String onlineId = htmlDecode(friendMatcher.group(1));
            Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION,
                    Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?",
                    new String[] { onlineId }, null);

            long friendId = -1;

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

            cv = new ContentValues(15);

            cv.put(Friends.DELETE_MARKER, updated);
            cv.put(Friends.ONLINE_STATUS, PSN.STATUS_PENDING);

            if (friendId < 0) {
                // New
                cv.put(Friends.ONLINE_ID, onlineId);
                cv.put(Friends.ACCOUNT_ID, accountId);
                cv.put(Friends.PROGRESS, 0);
                cv.putNull(Friends.ICON_URL);
                cv.put(Friends.LEVEL, 0);
                cv.put(Friends.TROPHIES_PLATINUM, 0);
                cv.put(Friends.TROPHIES_GOLD, 0);
                cv.put(Friends.TROPHIES_SILVER, 0);
                cv.put(Friends.TROPHIES_BRONZE, 0);
                cv.putNull(Friends.PLAYING);
                cv.put(Friends.LAST_UPDATED, 0);

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

                rowsUpdated++;
            }
        }

        // Handle rest of friends
        page = getResponse(URL_FRIENDS_AJAX);
        friendMatcher = PATTERN_FRIENDS.matcher(page);

        while (friendMatcher.find()) {
            String friendData = friendMatcher.group(1);

            String onlineId;
            if (!(m = PATTERN_FRIEND_ONLINE_ID.matcher(friendData)).find())
                continue;

            onlineId = htmlDecode(m.group(1));

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

            String iconUrl = null;
            if ((m = PATTERN_FRIEND_AVATAR.matcher(friendData)).find())
                iconUrl = getLargeAvatarIcon(resolveImageUrl(URL_FRIENDS_AJAX, m.group(1)));

            String comment = null;
            if ((m = PATTERN_FRIEND_COMMENT.matcher(friendData)).find()) {
                comment = htmlDecode(m.group(1));
                if (comment != null && comment.equals("null"))
                    comment = null;
            }

            int memberType = PSN.MEMBER_TYPE_FREE;
            if ((m = PATTERN_FRIEND_IS_PLUS.matcher(friendData)).find()
                    && m.group(1).equalsIgnoreCase("true")) {
                memberType = PSN.MEMBER_TYPE_PLUS;
            }

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

            m = PATTERN_FRIEND_TROPHY.matcher(friendData);
            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));
            }

            boolean inGame = false;
            int status = PSN.STATUS_OTHER;
            if ((m = PATTERN_FRIEND_STATUS.matcher(friendData)).find()) {
                String presence = m.group(1).toLowerCase();
                if (presence.equals("offline"))
                    status = PSN.STATUS_OFFLINE;
                else if (presence.equals("online"))
                    status = PSN.STATUS_ONLINE;
                else if (presence.equals("online-ingame")) {
                    status = PSN.STATUS_ONLINE;
                    inGame = true;
                } else if (presence.equals("online-away"))
                    status = PSN.STATUS_AWAY;
                else if (presence.equals("online-ingame-away")) {
                    status = PSN.STATUS_AWAY;
                    inGame = true;
                } else if (presence.equals("pending"))
                    status = PSN.STATUS_PENDING;
            }

            String playing = null;
            if ((m = PATTERN_FRIEND_PLAYING.matcher(friendData)).find()) {
                String activity = htmlDecode(m.group(1)).trim();

                if (activity != null && activity.length() > 0) {
                    if (inGame)
                        playing = mContext.getString(R.string.playing_f, activity);
                    else
                        playing = activity;
                }
            }

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

            long friendId = -1;

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

            cv = new ContentValues(15);

            cv.put(Friends.ICON_URL, iconUrl);
            cv.put(Friends.LEVEL, level);
            cv.put(Friends.MEMBER_TYPE, memberType);
            cv.put(Friends.COMMENT, comment);
            cv.put(Friends.LEVEL, level);
            cv.put(Friends.ONLINE_STATUS, status);
            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.PLAYING, playing);
            cv.put(Friends.DELETE_MARKER, updated);

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

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