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:gov.wa.wsdot.android.wsdot.service.FerriesTerminalSailingSpaceSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;//  w  w  w. ja  v a  2 s  .  c o  m
    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, new String[] { Caches.CACHE_LAST_UPDATED },
                Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "ferries_terminal_sailing_space" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            shouldUpdate = (Math.abs(now - lastUpdated) > (15 * DateUtils.SECOND_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();

        try {
            URL url = new URL(TERMINAL_SAILING_SPACE_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();

            JSONArray array = new JSONArray(jsonFile);
            List<ContentValues> terminal = new ArrayList<ContentValues>();

            int numItems = array.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = array.getJSONObject(j);
                ContentValues sailingSpaceValues = new ContentValues();
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_ID, item.getInt("TerminalID"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_NAME,
                        item.getString("TerminalName"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_ABBREV,
                        item.getString("TerminalAbbrev"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_DEPARTING_SPACES,
                        item.getString("DepartingSpaces"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_LAST_UPDATED,
                        dateFormat.format(new Date(System.currentTimeMillis())));

                if (starred.contains(item.getInt("TerminalID"))) {
                    sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_IS_STARRED, 1);
                }

                terminal.add(sailingSpaceValues);
            }

            // Purge existing terminal sailing space items covered by incoming data
            resolver.delete(FerriesTerminalSailingSpace.CONTENT_URI, null, null);
            // Bulk insert all the new terminal sailing space items
            resolver.bulkInsert(FerriesTerminalSailingSpace.CONTENT_URI,
                    terminal.toArray(new ContentValues[terminal.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[] { "ferries_terminal_sailing_space" });

            responseString = "OK";

        } catch (Exception e) {
            Log.e(TAG, "Error: " + e.getMessage());
            responseString = e.getMessage();
        }
    } else {
        responseString = "NOP";
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent
            .setAction("gov.wa.wsdot.android.wsdot.intent.action.FERRIES_TERMINAL_SAILING_SPACE_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);
}

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

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;//from w w  w .ja v a  2  s.c o 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, projection, Caches.CACHE_TABLE_NAME + " LIKE ?",
                new String[] { "cameras" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            //long deltaDays = (now - lastUpdated) / DateUtils.DAY_IN_MILLIS;
            //Log.d(DEBUG_TAG, "Delta since last update is " + deltaDays + " day(s)");
            shouldUpdate = (Math.abs(now - lastUpdated) > (7 * DateUtils.DAY_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();

        try {
            URL url = new URL(CAMERAS_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 jsonFile = "";
            String line;
            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("cameras");
            JSONArray items = result.getJSONArray("items");
            List<ContentValues> cams = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = items.getJSONObject(j);
                ContentValues cameraData = new ContentValues();

                cameraData.put(Cameras.CAMERA_ID, item.getString("id"));
                cameraData.put(Cameras.CAMERA_TITLE, item.getString("title"));
                cameraData.put(Cameras.CAMERA_URL, item.getString("url"));
                cameraData.put(Cameras.CAMERA_LATITUDE, item.getString("lat"));
                cameraData.put(Cameras.CAMERA_LONGITUDE, item.getString("lon"));
                cameraData.put(Cameras.CAMERA_HAS_VIDEO, item.getString("video"));
                cameraData.put(Cameras.CAMERA_ROAD_NAME, item.getString("roadName"));

                if (starred.contains(Integer.parseInt(item.getString("id")))) {
                    cameraData.put(Cameras.CAMERA_IS_STARRED, 1);
                }

                cams.add(cameraData);
            }

            // Purge existing cameras covered by incoming data
            resolver.delete(Cameras.CONTENT_URI, null, null);
            // Bulk insert all the new cameras
            resolver.bulkInsert(Cameras.CONTENT_URI, cams.toArray(new ContentValues[cams.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[] { "cameras" });

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

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

@SuppressLint("DefaultLocale")
@Override/*from   ww  w .  j a  va2 s .co 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:gov.wa.wsdot.android.wsdot.service.FerriesSchedulesSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;//from   w w w  . j  ava  2s.c  o m
    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, new String[] { Caches.CACHE_LAST_UPDATED },
                Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "ferries_schedules" }, 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) > (30 * 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();

        try {
            URL url = new URL(FERRIES_SCHEDULES_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 jsonFile = "";
            String line;

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

            JSONArray items = new JSONArray(jsonFile);
            List<ContentValues> schedules = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int i = 0; i < numItems; i++) {
                JSONObject item = items.getJSONObject(i);
                ContentValues schedule = new ContentValues();
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ID, item.getInt("RouteID"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_TITLE, item.getString("Description"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_DATE, item.getString("Date"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ALERT, item.getString("RouteAlert"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_UPDATED, dateFormat
                        .format(new Date(Long.parseLong(item.getString("CacheDate").substring(6, 19)))));

                if (starred.contains(item.getInt("RouteID"))) {
                    schedule.put(FerriesSchedules.FERRIES_SCHEDULE_IS_STARRED, 1);
                }

                schedules.add(schedule);
            }

            // Purge existing travel times covered by incoming data
            resolver.delete(FerriesSchedules.CONTENT_URI, null, null);
            // Bulk insert all the new travel times
            resolver.bulkInsert(FerriesSchedules.CONTENT_URI,
                    schedules.toArray(new ContentValues[schedules.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[] { "ferries_schedules" });

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

}

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

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;/*from w  w w.  j a v a  2s .c o 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[] { "travel_times" }, 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();
        }
    }

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

        try {
            URL url = new URL(TRAVEL_TIMES_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 jsonFile = "";
            String line;

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

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("traveltimes");
            JSONArray items = result.getJSONArray("items");
            List<ContentValues> times = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = items.getJSONObject(j);
                ContentValues timesValues = new ContentValues();
                timesValues.put(TravelTimes.TRAVEL_TIMES_TITLE, item.getString("title"));
                timesValues.put(TravelTimes.TRAVEL_TIMES_CURRENT, item.getInt("current"));
                timesValues.put(TravelTimes.TRAVEL_TIMES_AVERAGE, item.getInt("average"));
                timesValues.put(TravelTimes.TRAVEL_TIMES_DISTANCE, item.getString("distance") + " miles");
                timesValues.put(TravelTimes.TRAVEL_TIMES_ID, Integer.parseInt(item.getString("routeid")));
                timesValues.put(TravelTimes.TRAVEL_TIMES_UPDATED, item.getString("updated"));

                if (starred.contains(Integer.parseInt(item.getString("routeid")))) {
                    timesValues.put(TravelTimes.TRAVEL_TIMES_IS_STARRED, 1);
                }

                times.add(timesValues);
            }

            // Purge existing travel times covered by incoming data
            resolver.delete(TravelTimes.CONTENT_URI, null, null);
            // Bulk insert all the new travel times
            resolver.bulkInsert(TravelTimes.CONTENT_URI, times.toArray(new ContentValues[times.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[] { "travel_times" });

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

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

@SuppressLint("SimpleDateFormat")
@Override/* w w  w  . j a v  a2 s.  co  m*/
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:com.akop.bach.parser.PsnEuParser.java

@SuppressLint("DefaultLocale")
@Override/* w w  w . j  a  va 2  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: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  .  ja v a  2s .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.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;//from  ww w. j a va  2  s  .c o 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);
}