Example usage for com.google.gwt.jsonp.client JsonpRequestBuilder setTimeout

List of usage examples for com.google.gwt.jsonp.client JsonpRequestBuilder setTimeout

Introduction

In this page you can find the example usage for com.google.gwt.jsonp.client JsonpRequestBuilder setTimeout.

Prototype

public void setTimeout(int timeout) 

Source Link

Usage

From source file:gov.wa.wsdot.mobile.client.activities.ferries.vesselwatch.VesselWatchMapActivity.java

License:Open Source License

private void getCameras() {

    /** /*from ww w. ja  v a 2 s. c o  m*/
     * 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.
     */
    dbService.getCacheLastUpdated(Tables.CAMERAS, new ListCallback<GenericRow>() {

        @Override
        public void onFailure(DataServiceException error) {
        }

        @Override
        public void onSuccess(List<GenericRow> result) {
            boolean shouldUpdate = true;

            if (!result.isEmpty()) {
                double now = System.currentTimeMillis();
                double lastUpdated = result.get(0).getDouble(CachesColumns.CACHE_LAST_UPDATED);
                shouldUpdate = (Math.abs(now - lastUpdated) > (7 * 86400000)); // Refresh every 7 days.
            }

            view.showProgressIndicator();

            if (shouldUpdate) {
                JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
                // Set timeout for 30 seconds (30000 milliseconds)
                jsonp.setTimeout(30000);
                jsonp.requestObject(CAMERAS_URL, new AsyncCallback<CamerasFeed>() {

                    @Override
                    public void onFailure(Throwable caught) {
                        view.hideProgressIndicator();
                        phoneGap.getNotification().alert("Can't load data. Check your connection.",
                                new AlertCallback() {
                                    @Override
                                    public void onOkButtonClicked() {
                                        // TODO Auto-generated method stub
                                    }
                                }, "Connection Error");
                    }

                    @Override
                    public void onSuccess(final CamerasFeed result) {
                        if (result.getCameras() != null) {
                            final List<Integer> starred = new ArrayList<Integer>();

                            // Get any starred camera rows.
                            dbService.getStarredCameras(new ListCallback<GenericRow>() {

                                @Override
                                public void onFailure(DataServiceException error) {
                                    Window.alert(error.getMessage());
                                }

                                @Override
                                public void onSuccess(List<GenericRow> rows) {
                                    final ArrayList<CameraItem> cameraItems = new ArrayList<CameraItem>();
                                    CameraItem item;

                                    if (!rows.isEmpty()) {
                                        int numResults = rows.size();
                                        for (int i = 0; i < numResults; i++) {
                                            starred.add(rows.get(i).getInt(CamerasColumns.CAMERA_ID));
                                        }
                                    }

                                    //cameraItems.clear();
                                    int numCameras = result.getCameras().getItems().length();

                                    for (int i = 0; i < numCameras; i++) {
                                        item = new CameraItem();

                                        item.setCameraId(result.getCameras().getItems().get(i).getId());
                                        item.setTitle(result.getCameras().getItems().get(i).getTitle());
                                        item.setImageUrl(result.getCameras().getItems().get(i).getUrl());
                                        item.setLatitude(result.getCameras().getItems().get(i).getLat());
                                        item.setLongitude(result.getCameras().getItems().get(i).getLon());
                                        item.setHasVideo(result.getCameras().getItems().get(i).getHasVideo());
                                        item.setRoadName(result.getCameras().getItems().get(i).getRoadName());

                                        if (starred.contains(result.getCameras().getItems().get(i).getId())) {
                                            item.setIsStarred(1);
                                        }

                                        cameraItems.add(item);
                                    }

                                    // Purge existing cameras covered by incoming data
                                    dbService.deleteCameras(new VoidCallback() {

                                        @Override
                                        public void onFailure(DataServiceException error) {
                                        }

                                        @Override
                                        public void onSuccess() {
                                            // Bulk insert all the new cameras
                                            dbService.insertCameras(cameraItems, new RowIdListCallback() {

                                                @Override
                                                public void onFailure(DataServiceException error) {
                                                }

                                                @Override
                                                public void onSuccess(List<Integer> rowIds) {
                                                    // Update the cache table with the time we did the update
                                                    ArrayList<CacheItem> cacheItems = new ArrayList<CacheItem>();
                                                    cacheItems.add(new CacheItem(Tables.CAMERAS,
                                                            System.currentTimeMillis()));

                                                    dbService.updateCachesTable(cacheItems, new VoidCallback() {

                                                        @Override
                                                        public void onFailure(DataServiceException error) {
                                                        }

                                                        @Override
                                                        public void onSuccess() {
                                                            view.hideProgressIndicator();
                                                            drawCamerasLayer();
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    }
                });

            } else {
                view.hideProgressIndicator();
                drawCamerasLayer();
            }
        }
    });
}

From source file:gov.wa.wsdot.mobile.client.activities.ferries.vesselwatch.VesselWatchMapActivity.java

License:Open Source License

private void drawVesselsLayer() {

    JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
    // Set timeout for 25 seconds (25000 milliseconds)
    jsonp.setTimeout(25000);
    jsonp.requestObject(VESSEL_WATCH_URL, new AsyncCallback<VesselWatchFeed>() {

        @Override/*w  ww. j  a  va  2s  . com*/
        public void onFailure(Throwable caught) {
            view.hideProgressIndicator();
            phoneGap.getNotification().alert("Can't load data. Check your connection.", new AlertCallback() {
                @Override
                public void onOkButtonClicked() {
                    // TODO Auto-generated method stub
                }
            }, "Connection Error");
        }

        @Override
        public void onSuccess(VesselWatchFeed result) {

            vesselWatchItems.clear();
            VesselWatchItem item = null;

            if (result != null) {
                int numEntries = result.length();
                for (int i = 0; i < numEntries; i++) {
                    item = new VesselWatchItem();

                    if (!result.get(i).getInService()) {
                        continue;
                    }

                    item.setVesselID(result.get(i).getVesselID());
                    item.setName(result.get(i).getName());
                    item.setRoute(result.get(i).getRoute());
                    item.setLastDock(result.get(i).getLastDock());
                    item.setArrivingTerminal(result.get(i).getATerm());
                    item.setLeftDock(result.get(i).getLeftDock());
                    item.setNextDep(result.get(i).getNextDep());
                    item.setEta(result.get(i).getEta());
                    item.setHead(result.get(i).getHead());
                    item.setSpeed(result.get(i).getSpeed());

                    // round heading to nearest 30 degrees
                    int nearest = (result.get(i).getHead() + 30 / 2) / 30 * 30;

                    item.setIcon(ferryIcons.get(nearest));
                    item.setLat(result.get(i).getLat());
                    item.setLon(result.get(i).getLon());

                    vesselWatchItems.add(item);

                }

                view.drawFerries(vesselWatchItems);

            }

        }
    });

}

From source file:gov.wa.wsdot.mobile.client.activities.home.HomeActivity.java

License:Open Source License

private void createAlertsList() {

    /** /* w ww  .j a  v a 2 s. c  o m*/
     * 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.
     */
    dbService.getCacheLastUpdated(Tables.HIGHWAY_ALERTS, new ListCallback<GenericRow>() {

        @Override
        public void onFailure(DataServiceException error) {
            // On first install the 'caches' table doesn't exist yet. Why?
            highwayAlertItems.clear();
            highwayAlertItems.add(new HighwayAlertItem(-1, "No highest impact travel alerts"));
            view.hideProgressIndicator();
            view.render(highwayAlertItems);
            view.refresh();
        }

        @Override
        public void onSuccess(List<GenericRow> result) {
            boolean shouldUpdate = true;

            if (!result.isEmpty()) {
                double now = System.currentTimeMillis();
                double lastUpdated = result.get(0).getDouble(CachesColumns.CACHE_LAST_UPDATED);
                shouldUpdate = (Math.abs(now - lastUpdated) > (5 * 60000)); // Refresh every 5 minutes.
            }

            view.showProgressIndicator();
            view.clear();

            if (shouldUpdate) {
                try {
                    JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
                    // Set timeout for 30 seconds (30000 milliseconds)
                    jsonp.setTimeout(30000);
                    jsonp.requestObject(HIGHWAY_ALERTS_URL, new AsyncCallback<HighwayAlerts>() {

                        @Override
                        public void onFailure(Throwable caught) {
                            highwayAlertItems.clear();
                            highwayAlertItems
                                    .add(new HighwayAlertItem(-1, "Can't load data. Check your connection."));
                            view.hideProgressIndicator();
                            view.render(highwayAlertItems);
                            view.refresh();
                        }

                        @Override
                        public void onSuccess(HighwayAlerts result) {
                            highwayAlertItems.clear();

                            if (result.getAlerts() != null) {
                                HighwayAlertItem item;
                                int size = result.getAlerts().getItems().length();

                                for (int i = 0; i < size; i++) {
                                    item = new HighwayAlertItem();

                                    item.setAlertId(result.getAlerts().getItems().get(i).getAlertID());
                                    item.setHeadlineDescription(
                                            result.getAlerts().getItems().get(i).getHeadlineDescription());
                                    item.setEventCategory(
                                            result.getAlerts().getItems().get(i).getEventCategory());
                                    item.setPriority(result.getAlerts().getItems().get(i).getPriority());
                                    item.setStartLatitude(result.getAlerts().getItems().get(i)
                                            .getStartRoadwayLocation().getLatitude());
                                    item.setStartLongitude(result.getAlerts().getItems().get(i)
                                            .getStartRoadwayLocation().getLongitude());
                                    item.setStartRoadName(result.getAlerts().getItems().get(i)
                                            .getStartRoadwayLocation().getRoadName());
                                    item.setLastUpdatedTime(dateFormat
                                            .format(new Date(Long.parseLong(result.getAlerts().getItems().get(i)
                                                    .getLastUpdatedTime().substring(6, 19)))));

                                    highwayAlertItems.add(item);
                                }

                                // Purge existing highway alerts covered by incoming data
                                dbService.deleteHighwayAlerts(new VoidCallback() {

                                    @Override
                                    public void onFailure(DataServiceException error) {
                                    }

                                    @Override
                                    public void onSuccess() {
                                        // Bulk insert all the new highway alerts
                                        dbService.insertHighwayAlerts(highwayAlertItems,
                                                new RowIdListCallback() {

                                                    @Override
                                                    public void onFailure(DataServiceException error) {
                                                        highwayAlertItems.clear();
                                                        highwayAlertItems.add(
                                                                new HighwayAlertItem(-1, error.getMessage()));
                                                        view.hideProgressIndicator();
                                                        view.render(highwayAlertItems);
                                                        view.refresh();
                                                    }

                                                    @Override
                                                    public void onSuccess(List<Integer> rowIds) {
                                                        // Update the cache table with the time we did the update
                                                        List<CacheItem> cacheItems = new ArrayList<CacheItem>();
                                                        cacheItems.add(new CacheItem(Tables.HIGHWAY_ALERTS,
                                                                System.currentTimeMillis()));
                                                        dbService.updateCachesTable(cacheItems,
                                                                new VoidCallback() {

                                                                    @Override
                                                                    public void onFailure(
                                                                            DataServiceException error) {
                                                                    }

                                                                    @Override
                                                                    public void onSuccess() {
                                                                        dbService.getHighwayAlerts(
                                                                                new ListCallback<GenericRow>() {

                                                                                    @Override
                                                                                    public void onFailure(
                                                                                            DataServiceException error) {
                                                                                    }

                                                                                    @Override
                                                                                    public void onSuccess(
                                                                                            List<GenericRow> result) {
                                                                                        getHighestPriorityHighwayAlerts(
                                                                                                result);
                                                                                    }
                                                                                });
                                                                    }

                                                                });
                                                    }
                                                });
                                    }
                                });
                            }
                        }
                    });

                } catch (Exception e) {

                }
            } else {

                dbService.getHighwayAlerts(new ListCallback<GenericRow>() {

                    @Override
                    public void onFailure(DataServiceException error) {
                    }

                    @Override
                    public void onSuccess(List<GenericRow> result) {
                        getHighestPriorityHighwayAlerts(result);
                    }
                });
            }
        }
    });

}

From source file:gov.wa.wsdot.mobile.client.activities.home.HomeActivity.java

License:Open Source License

private void createFavoritesList() {

    getFavoriteLocations();/*from ww w  .j  ava2  s .c o m*/

    dbService.getStarredCameras(new ListCallback<GenericRow>() {

        @Override
        public void onFailure(DataServiceException error) {

        }

        @Override
        public void onSuccess(List<GenericRow> result) {

            if (!result.isEmpty()) {
                cameraItems.clear();
                CameraItem c;

                for (GenericRow camera : result) {
                    c = new CameraItem();

                    c.setCameraId(camera.getInt(CamerasColumns.CAMERA_ID));
                    c.setTitle(camera.getString(CamerasColumns.CAMERA_TITLE));

                    cameraItems.add(c);
                }

                view.hideEmptyFavoritesMessage();
                view.showCamerasHeader();
                view.showCamerasList();
                view.renderCameras(cameraItems);
                view.refresh();
                accessibility.postScreenChangeNotification();

            } else {
                view.hideCamerasHeader();
                view.hideCamerasList();
            }

        }
    });

    dbService.getStarredFerriesSchedules(new ListCallback<GenericRow>() {

        @Override
        public void onFailure(DataServiceException error) {
        }

        @Override
        public void onSuccess(final List<GenericRow> starredFerriesSchedules) {
            if (!starredFerriesSchedules.isEmpty()) {
                /** 
                 * 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.
                 */
                dbService.getCacheLastUpdated(Tables.FERRIES_SCHEDULES, new ListCallback<GenericRow>() {

                    @Override
                    public void onFailure(DataServiceException error) {
                    }

                    @Override
                    public void onSuccess(List<GenericRow> result) {
                        boolean shouldUpdate = true;

                        if (!result.isEmpty()) {
                            double now = System.currentTimeMillis();
                            double lastUpdated = result.get(0).getDouble(CachesColumns.CACHE_LAST_UPDATED);
                            shouldUpdate = (Math.abs(now - lastUpdated) > (30 * 60000)); // Refresh every 30 minutes.
                        }

                        //view.showProgressBar();

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

                            for (GenericRow row : starredFerriesSchedules) {
                                starred.add(row.getInt(FerriesSchedulesColumns.FERRIES_SCHEDULE_ID));
                            }

                            JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
                            // Set timeout for 30 seconds (30000 milliseconds)
                            jsonp.setTimeout(30000);
                            jsonp.requestObject(FERRIES_SCHEDULES_URL, new AsyncCallback<FerriesRouteFeed>() {

                                @Override
                                public void onFailure(Throwable caught) {
                                    //view.hideProgressBar();
                                    phoneGap.getNotification().alert("Can't load data. Check your connection.",
                                            new AlertCallback() {
                                                @Override
                                                public void onOkButtonClicked() {
                                                    // TODO Auto-generated method stub
                                                }
                                            }, "Connection Error");
                                }

                                @Override
                                public void onSuccess(FerriesRouteFeed result) {

                                    if (result.getRoutes() != null) {
                                        ferriesRouteItems.clear();
                                        FerriesRouteItem item;
                                        int numRoutes = result.getRoutes().length();

                                        for (int i = 0; i < numRoutes; i++) {
                                            item = new FerriesRouteItem();

                                            item.setRouteID(result.getRoutes().get(i).getRouteID());
                                            item.setDescription(result.getRoutes().get(i).getDescription());
                                            item.setCrossingTime(result.getRoutes().get(i).getCrossingTime());
                                            item.setScheduleDate(
                                                    new JSONArray(result.getRoutes().get(i).getDate())
                                                            .toString());
                                            item.setRouteAlert(
                                                    new JSONArray(result.getRoutes().get(i).getRouteAlert())
                                                            .toString());
                                            item.setCacheDate(dateFormat.format(new Date(Long.parseLong(result
                                                    .getRoutes().get(i).getCacheDate().substring(6, 19)))));

                                            if (starred.contains(result.getRoutes().get(i).getRouteID())) {
                                                item.setIsStarred(1);
                                            }

                                            ferriesRouteItems.add(item);
                                        }

                                        // Purge existing border wait times covered by incoming data
                                        dbService.deleteFerriesSchedules(new VoidCallback() {

                                            @Override
                                            public void onFailure(DataServiceException error) {
                                            }

                                            @Override
                                            public void onSuccess() {
                                                // Bulk insert all the new ferries schedules
                                                dbService.insertFerriesSchedules(ferriesRouteItems,
                                                        new RowIdListCallback() {

                                                            @Override
                                                            public void onFailure(DataServiceException error) {
                                                            }

                                                            @Override
                                                            public void onSuccess(List<Integer> rowIds) {
                                                                // Update the cache table with the time we did the update
                                                                List<CacheItem> cacheItems = new ArrayList<CacheItem>();
                                                                cacheItems.add(
                                                                        new CacheItem(Tables.FERRIES_SCHEDULES,
                                                                                System.currentTimeMillis()));
                                                                dbService.updateCachesTable(cacheItems,
                                                                        new VoidCallback() {

                                                                            @Override
                                                                            public void onFailure(
                                                                                    DataServiceException error) {
                                                                            }

                                                                            @Override
                                                                            public void onSuccess() {

                                                                                dbService
                                                                                        .getStarredFerriesSchedules(
                                                                                                new ListCallback<GenericRow>() {

                                                                                                    @Override
                                                                                                    public void onFailure(
                                                                                                            DataServiceException error) {
                                                                                                    }

                                                                                                    @Override
                                                                                                    public void onSuccess(
                                                                                                            final List<GenericRow> starredMountainPassRows) {
                                                                                                        getFerriesSchedules(
                                                                                                                starredFerriesSchedules);
                                                                                                    }
                                                                                                });
                                                                            }
                                                                        });
                                                            }
                                                        });
                                            }
                                        });
                                    }
                                }
                            });

                        } else {
                            getFerriesSchedules(starredFerriesSchedules);
                        }

                    }
                });

            } else {
                view.hideFerriesHeader();
                view.hideFerriesList();
            }
        }
    });

    dbService.getStarredMountainPasses(new ListCallback<GenericRow>() {

        @Override
        public void onFailure(DataServiceException error) {
        }

        @Override
        public void onSuccess(final List<GenericRow> starredMountainPassRows) {
            if (!starredMountainPassRows.isEmpty()) {
                /** 
                 * 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.
                 */
                dbService.getCacheLastUpdated(Tables.MOUNTAIN_PASSES, new ListCallback<GenericRow>() {

                    @Override
                    public void onFailure(DataServiceException error) {
                    }

                    @Override
                    public void onSuccess(List<GenericRow> result) {
                        boolean shouldUpdate = true;

                        if (!result.isEmpty()) {
                            double now = System.currentTimeMillis();
                            double lastUpdated = result.get(0).getDouble(CachesColumns.CACHE_LAST_UPDATED);
                            shouldUpdate = (Math.abs(now - lastUpdated) > (15 * 60000)); // Refresh every 15 minutes.
                        }

                        //view.showProgressBar();

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

                            for (GenericRow row : starredMountainPassRows) {
                                starred.add(row.getInt(MountainPassesColumns.MOUNTAIN_PASS_ID));
                            }

                            JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
                            // Set timeout for 30 seconds (30000 milliseconds)
                            jsonp.setTimeout(30000);
                            jsonp.requestObject(MOUNTAIN_PASS_URL, new AsyncCallback<MountainPassConditions>() {

                                @Override
                                public void onFailure(Throwable caught) {
                                    //view.hideProgressBar();
                                    phoneGap.getNotification().alert("Can't load data. Check your connection.",
                                            new AlertCallback() {
                                                @Override
                                                public void onOkButtonClicked() {
                                                    // TODO Auto-generated method stub
                                                }
                                            }, "Connection Error");
                                }

                                @Override
                                public void onSuccess(MountainPassConditions result) {
                                    mountainPassItems.clear();

                                    if (result.getMountainPassConditionsResult() != null) {
                                        MountainPassItem item;

                                        String weatherCondition;
                                        String weatherImage;
                                        String forecast_weather_image;

                                        String mDateUpdated = "";

                                        int numConditions = result.getMountainPassConditionsResult()
                                                .getPassCondition().length();

                                        for (int i = 0; i < numConditions; i++) {
                                            item = new MountainPassItem();

                                            weatherCondition = result.getMountainPassConditionsResult()
                                                    .getPassCondition().get(i).getWeatherCondition();
                                            weatherImage = getWeatherImage(weatherPhrases, weatherCondition);

                                            JsArrayInteger dateUpdated = result
                                                    .getMountainPassConditionsResult().getPassCondition().get(i)
                                                    .getDateUpdated();

                                            try {
                                                StringBuilder sb = new StringBuilder();
                                                for (int j = 0; j < 5; j++) {
                                                    sb.append(dateUpdated.get(j));
                                                    sb.append(",");
                                                }
                                                String tempDate = sb.toString().trim();
                                                tempDate = tempDate.substring(0, tempDate.length() - 1);
                                                Date date = parseDateFormat.parse(tempDate);
                                                mDateUpdated = dateFormat.format(date);
                                            } catch (Exception e) {
                                                mDateUpdated = "N/A";
                                            }

                                            JsArray<Forecast> forecasts = result
                                                    .getMountainPassConditionsResult().getPassCondition().get(i)
                                                    .getForecast();
                                            int numForecasts = forecasts.length();

                                            for (int k = 0; k < numForecasts; k++) {
                                                Forecast forecast = forecasts.get(k);

                                                if (isNight(forecast.getDay())) {
                                                    forecast_weather_image = getWeatherImage(
                                                            weatherPhrasesNight, forecast.getForecastText());
                                                } else {
                                                    forecast_weather_image = getWeatherImage(weatherPhrases,
                                                            forecast.getForecastText());
                                                }

                                                forecast.setWeatherIcon(forecast_weather_image);

                                                if (k == 0) {
                                                    if (weatherCondition.equals("")) {
                                                        weatherCondition = forecast.getForecastText()
                                                                .split("\\.")[0] + ".";
                                                        weatherImage = forecast_weather_image;
                                                    }
                                                }

                                                forecasts.set(k, forecast);

                                            }

                                            item.setWeatherCondition(weatherCondition);
                                            item.setElevationInFeet(result.getMountainPassConditionsResult()
                                                    .getPassCondition().get(i).getElevationInFeet());
                                            item.setMountainPassId(result.getMountainPassConditionsResult()
                                                    .getPassCondition().get(i).getMountainPassId());
                                            item.setRoadCondition(result.getMountainPassConditionsResult()
                                                    .getPassCondition().get(i).getRoadCondition());
                                            item.setTemperatureInFahrenheit(
                                                    result.getMountainPassConditionsResult().getPassCondition()
                                                            .get(i).getTemperatureInFahrenheit());
                                            item.setDateUpdated(mDateUpdated);
                                            item.setMountainPassName(result.getMountainPassConditionsResult()
                                                    .getPassCondition().get(i).getMountainPassName());
                                            item.setWeatherIcon(weatherImage);
                                            item.setRestrictionOneText(
                                                    result.getMountainPassConditionsResult().getPassCondition()
                                                            .get(i).getRestrictionOne().getRestrictionText());
                                            item.setRestrictionOneTravelDirection(
                                                    result.getMountainPassConditionsResult().getPassCondition()
                                                            .get(i).getRestrictionOne().getTravelDirection());
                                            item.setRestrictionTwoText(
                                                    result.getMountainPassConditionsResult().getPassCondition()
                                                            .get(i).getRestrictionTwo().getRestrictionText());
                                            item.setRestrictionTwoTravelDirection(
                                                    result.getMountainPassConditionsResult().getPassCondition()
                                                            .get(i).getRestrictionTwo().getTravelDirection());
                                            item.setCamera(
                                                    new JSONArray(result.getMountainPassConditionsResult()
                                                            .getPassCondition().get(i).getCameras())
                                                                    .toString());
                                            item.setForecast(new JSONArray(forecasts).toString());

                                            if (starred.contains(result.getMountainPassConditionsResult()
                                                    .getPassCondition().get(i).getMountainPassId())) {
                                                item.setIsStarred(1);
                                            }

                                            mountainPassItems.add(item);
                                        }

                                        // Purge existing mountain passes covered by incoming data
                                        dbService.deleteMountainPasses(new VoidCallback() {

                                            @Override
                                            public void onFailure(DataServiceException error) {
                                            }

                                            @Override
                                            public void onSuccess() {
                                                // Bulk insert all the new mountain passes
                                                dbService.insertMountainPasses(mountainPassItems,
                                                        new RowIdListCallback() {

                                                            @Override
                                                            public void onFailure(DataServiceException error) {
                                                            }

                                                            @Override
                                                            public void onSuccess(List<Integer> rowIds) {
                                                                // Update the cache table with the time we did the update
                                                                ArrayList<CacheItem> cacheItems = new ArrayList<CacheItem>();
                                                                cacheItems.add(
                                                                        new CacheItem(Tables.MOUNTAIN_PASSES,
                                                                                System.currentTimeMillis()));

                                                                dbService.updateCachesTable(cacheItems,
                                                                        new VoidCallback() {

                                                                            @Override
                                                                            public void onFailure(
                                                                                    DataServiceException error) {
                                                                            }

                                                                            @Override
                                                                            public void onSuccess() {

                                                                                dbService
                                                                                        .getStarredMountainPasses(
                                                                                                new ListCallback<GenericRow>() {

                                                                                                    @Override
                                                                                                    public void onFailure(
                                                                                                            DataServiceException error) {
                                                                                                    }

                                                                                                    @Override
                                                                                                    public void onSuccess(
                                                                                                            final List<GenericRow> starredMountainPassRows) {
                                                                                                        getMountainPasses(
                                                                                                                starredMountainPassRows);
                                                                                                    }
                                                                                                });

                                                                            }
                                                                        });
                                                            }
                                                        });
                                            }
                                        });
                                    }
                                }
                            });

                        } else {
                            getMountainPasses(starredMountainPassRows);
                        }
                    }
                });

            } else {
                view.hideMountainPassesHeader();
                view.hideMountainPassesList();
            }

        }
    });

    dbService.getStarredTravelTimes(new ListCallback<GenericRow>() {

        @Override
        public void onFailure(DataServiceException error) {
        }

        @Override
        public void onSuccess(final List<GenericRow> starredTravelTimesRows) {
            if (!starredTravelTimesRows.isEmpty()) {
                /** 
                 * 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.
                 */
                dbService.getCacheLastUpdated(Tables.TRAVEL_TIMES, new ListCallback<GenericRow>() {

                    @Override
                    public void onFailure(DataServiceException error) {
                    }

                    @Override
                    public void onSuccess(List<GenericRow> result) {
                        boolean shouldUpdate = true;

                        if (!result.isEmpty()) {
                            double now = System.currentTimeMillis();
                            double lastUpdated = result.get(0).getDouble(CachesColumns.CACHE_LAST_UPDATED);
                            shouldUpdate = (Math.abs(now - lastUpdated) > (5 * 60000)); // Refresh every 5 minutes.
                        }

                        //view.showProgressBar();

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

                            for (GenericRow row : starredTravelTimesRows) {
                                starred.add(row.getInt(TravelTimesColumns.TRAVEL_TIMES_ID));
                            }

                            JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
                            // Set timeout for 30 seconds (30000 milliseconds)
                            jsonp.setTimeout(30000);
                            jsonp.requestObject(TRAVEL_TIMES_URL, new AsyncCallback<TravelTimes>() {

                                @Override
                                public void onFailure(Throwable caught) {
                                    //view.hideProgressBar();
                                    phoneGap.getNotification().alert("Can't load data. Check your connection.",
                                            new AlertCallback() {
                                                @Override
                                                public void onOkButtonClicked() {
                                                    // TODO Auto-generated method stub
                                                }
                                            }, "Connection Error");
                                }

                                @Override
                                public void onSuccess(TravelTimes result) {

                                    if (result.getTravelTimes() != null) {
                                        travelTimesItems.clear();
                                        TravelTimesItem item;

                                        int numItems = result.getTravelTimes().getItems().length();

                                        for (int i = 0; i < numItems; i++) {
                                            item = new TravelTimesItem();

                                            item.setDistance(
                                                    result.getTravelTimes().getItems().get(i).getDistance());
                                            item.setUpdated(
                                                    result.getTravelTimes().getItems().get(i).getUpdated());
                                            item.setTitle(result.getTravelTimes().getItems().get(i).getTitle());
                                            item.setAverageTime(
                                                    result.getTravelTimes().getItems().get(i).getAverage());
                                            item.setRouteId(Integer.parseInt(
                                                    result.getTravelTimes().getItems().get(i).getRouteId(),
                                                    10));
                                            item.setCurrentTime(
                                                    result.getTravelTimes().getItems().get(i).getCurrent());

                                            if (starred.contains(Integer.parseInt(
                                                    result.getTravelTimes().getItems().get(i).getRouteId(),
                                                    10))) {
                                                item.setIsStarred(1);
                                            }

                                            travelTimesItems.add(item);
                                        }

                                        // Purge existing mountain passes covered by incoming data
                                        dbService.deleteTravelTimes(new VoidCallback() {

                                            @Override
                                            public void onFailure(DataServiceException error) {
                                            }

                                            @Override
                                            public void onSuccess() {
                                                // Bulk insert all the new travel times
                                                dbService.insertTravelTimes(travelTimesItems,
                                                        new RowIdListCallback() {

                                                            @Override
                                                            public void onFailure(DataServiceException error) {
                                                            }

                                                            @Override
                                                            public void onSuccess(List<Integer> rowIds) {
                                                                // Update the cache table with the time we did the update
                                                                ArrayList<CacheItem> cacheItems = new ArrayList<CacheItem>();
                                                                cacheItems
                                                                        .add(new CacheItem(Tables.TRAVEL_TIMES,
                                                                                System.currentTimeMillis()));

                                                                dbService.updateCachesTable(cacheItems,
                                                                        new VoidCallback() {

                                                                            @Override
                                                                            public void onFailure(
                                                                                    DataServiceException error) {
                                                                            }

                                                                            @Override
                                                                            public void onSuccess() {

                                                                                dbService.getStarredTravelTimes(
                                                                                        new ListCallback<GenericRow>() {

                                                                                            @Override
                                                                                            public void onFailure(
                                                                                                    DataServiceException error) {
                                                                                            }

                                                                                            @Override
                                                                                            public void onSuccess(
                                                                                                    final List<GenericRow> starredMountainPassRows) {
                                                                                                getTravelTimes(
                                                                                                        starredTravelTimesRows);
                                                                                            }
                                                                                        });
                                                                            }
                                                                        });
                                                            }
                                                        });
                                            }
                                        });
                                    }
                                }
                            });

                        } else {
                            getTravelTimes(starredTravelTimesRows);
                        }

                    }
                });

            } else {
                view.hideTravelTimesHeader();
                view.hideTravelTimesList();
            }
        }
    });

    view.showEmptyFavoritesMessage();
}

From source file:gov.wa.wsdot.mobile.client.activities.mountainpasses.MountainPassesActivity.java

License:Open Source License

private void createTopicsList(final boolean forceUpdate) {

    /** //from  w w w .j  a  va  2  s  .  com
     * 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.
     */
    dbService.getCacheLastUpdated(Tables.MOUNTAIN_PASSES, new ListCallback<GenericRow>() {

        @Override
        public void onFailure(DataServiceException error) {
        }

        @Override
        public void onSuccess(List<GenericRow> result) {
            boolean shouldUpdate = true;

            if (!result.isEmpty()) {
                double now = System.currentTimeMillis();
                double lastUpdated = result.get(0).getDouble(CachesColumns.CACHE_LAST_UPDATED);
                shouldUpdate = (Math.abs(now - lastUpdated) > (15 * 60000)); // Refresh every 15 minutes.
            }

            view.showProgressIndicator();

            if (shouldUpdate || forceUpdate) {
                /**
                 * Check the mountain passes table for any starred entries. If we find some,
                 * save them to a list so we can re-star those after we flush the database.
                 */
                dbService.getStarredMountainPasses(new ListCallback<GenericRow>() {

                    @Override
                    public void onFailure(DataServiceException error) {
                    }

                    @Override
                    public void onSuccess(List<GenericRow> result) {
                        starred.clear();

                        if (!result.isEmpty()) {
                            for (GenericRow row : result) {
                                starred.add(row.getInt(MountainPassesColumns.MOUNTAIN_PASS_ID));
                            }
                        }

                        JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
                        // Set timeout for 30 seconds (30000 milliseconds)
                        jsonp.setTimeout(30000);
                        jsonp.requestObject(MOUNTAIN_PASS_URL, new AsyncCallback<MountainPassConditions>() {

                            @Override
                            public void onFailure(Throwable caught) {
                                view.hideProgressIndicator();
                                if (!alertShowing) {
                                    alertShowing = true;
                                    phoneGap.getNotification().alert("Can't load data. Check your connection.",
                                            new AlertCallback() {
                                                @Override
                                                public void onOkButtonClicked() {
                                                    alertShowing = false;
                                                }
                                            }, "Connection Error");
                                }
                            }

                            @Override
                            public void onSuccess(MountainPassConditions result) {
                                mountainPassItems.clear();

                                if (result.getMountainPassConditionsResult() != null) {
                                    MountainPassItem item;

                                    String weatherCondition;
                                    String weatherImage;
                                    String forecast_weather_image;

                                    String mDateUpdated = "";

                                    int numConditions = result.getMountainPassConditionsResult()
                                            .getPassCondition().length();

                                    for (int i = 0; i < numConditions; i++) {
                                        item = new MountainPassItem();

                                        weatherCondition = result.getMountainPassConditionsResult()
                                                .getPassCondition().get(i).getWeatherCondition();
                                        weatherImage = getWeatherImage(weatherPhrases, weatherCondition);

                                        JsArrayInteger dateUpdated = result.getMountainPassConditionsResult()
                                                .getPassCondition().get(i).getDateUpdated();

                                        try {
                                            StringBuilder sb = new StringBuilder();
                                            for (int j = 0; j < 5; j++) {
                                                sb.append(dateUpdated.get(j));
                                                sb.append(",");
                                            }
                                            String tempDate = sb.toString().trim();
                                            tempDate = tempDate.substring(0, tempDate.length() - 1);
                                            Date date = parseDateFormat.parse(tempDate);
                                            mDateUpdated = displayDateFormat.format(date);
                                        } catch (Exception e) {
                                            mDateUpdated = "N/A";
                                        }

                                        JsArray<Forecast> forecasts = result.getMountainPassConditionsResult()
                                                .getPassCondition().get(i).getForecast();
                                        int numForecasts = forecasts.length();

                                        for (int k = 0; k < numForecasts; k++) {
                                            Forecast forecast = forecasts.get(k);

                                            if (isNight(forecast.getDay())) {
                                                forecast_weather_image = getWeatherImage(weatherPhrasesNight,
                                                        forecast.getForecastText());
                                            } else {
                                                forecast_weather_image = getWeatherImage(weatherPhrases,
                                                        forecast.getForecastText());
                                            }

                                            forecast.setWeatherIcon(forecast_weather_image);

                                            if (k == 0) {
                                                if (weatherCondition.equals("")) {
                                                    weatherCondition = forecast.getForecastText()
                                                            .split("\\.")[0] + ".";
                                                    weatherImage = forecast_weather_image;
                                                }
                                            }

                                            forecasts.set(k, forecast);

                                        }

                                        item.setWeatherCondition(weatherCondition);
                                        item.setElevationInFeet(result.getMountainPassConditionsResult()
                                                .getPassCondition().get(i).getElevationInFeet());
                                        item.setMountainPassId(result.getMountainPassConditionsResult()
                                                .getPassCondition().get(i).getMountainPassId());
                                        item.setRoadCondition(result.getMountainPassConditionsResult()
                                                .getPassCondition().get(i).getRoadCondition());
                                        item.setTemperatureInFahrenheit(result.getMountainPassConditionsResult()
                                                .getPassCondition().get(i).getTemperatureInFahrenheit());
                                        item.setDateUpdated(mDateUpdated);
                                        item.setMountainPassName(result.getMountainPassConditionsResult()
                                                .getPassCondition().get(i).getMountainPassName());
                                        item.setWeatherIcon(weatherImage);
                                        item.setRestrictionOneText(
                                                result.getMountainPassConditionsResult().getPassCondition()
                                                        .get(i).getRestrictionOne().getRestrictionText());
                                        item.setRestrictionOneTravelDirection(
                                                result.getMountainPassConditionsResult().getPassCondition()
                                                        .get(i).getRestrictionOne().getTravelDirection());
                                        item.setRestrictionTwoText(
                                                result.getMountainPassConditionsResult().getPassCondition()
                                                        .get(i).getRestrictionTwo().getRestrictionText());
                                        item.setRestrictionTwoTravelDirection(
                                                result.getMountainPassConditionsResult().getPassCondition()
                                                        .get(i).getRestrictionTwo().getTravelDirection());
                                        item.setCamera(new JSONArray(result.getMountainPassConditionsResult()
                                                .getPassCondition().get(i).getCameras()).toString());
                                        item.setForecast(new JSONArray(forecasts).toString());

                                        if (starred.contains(result.getMountainPassConditionsResult()
                                                .getPassCondition().get(i).getMountainPassId())) {
                                            item.setIsStarred(1);
                                        }

                                        mountainPassItems.add(item);
                                    }

                                    // Purge existing mountain passes covered by incoming data
                                    dbService.deleteMountainPasses(new VoidCallback() {

                                        @Override
                                        public void onFailure(DataServiceException error) {
                                        }

                                        @Override
                                        public void onSuccess() {
                                            // Bulk insert all the new mountain passes
                                            dbService.insertMountainPasses(mountainPassItems,
                                                    new RowIdListCallback() {

                                                        @Override
                                                        public void onFailure(DataServiceException error) {
                                                        }

                                                        @Override
                                                        public void onSuccess(List<Integer> rowIds) {
                                                            // Update the cache table with the time we did the update
                                                            ArrayList<CacheItem> cacheItems = new ArrayList<CacheItem>();
                                                            cacheItems.add(new CacheItem(Tables.MOUNTAIN_PASSES,
                                                                    System.currentTimeMillis()));

                                                            dbService.updateCachesTable(cacheItems,
                                                                    new VoidCallback() {

                                                                        @Override
                                                                        public void onFailure(
                                                                                DataServiceException error) {
                                                                        }

                                                                        @Override
                                                                        public void onSuccess() {
                                                                            dbService.getMountainPasses(
                                                                                    new ListCallback<GenericRow>() {

                                                                                        @Override
                                                                                        public void onFailure(
                                                                                                DataServiceException error) {
                                                                                        }

                                                                                        @Override
                                                                                        public void onSuccess(
                                                                                                List<GenericRow> result) {
                                                                                            getMountainPasses(
                                                                                                    result);
                                                                                        }

                                                                                    });
                                                                        }
                                                                    });
                                                        }
                                                    });
                                        }
                                    });
                                }
                            }
                        });
                    }
                });

            } else {
                dbService.getMountainPasses(new ListCallback<GenericRow>() {

                    @Override
                    public void onFailure(DataServiceException error) {
                    }

                    @Override
                    public void onSuccess(List<GenericRow> result) {
                        getMountainPasses(result);
                    }

                });
            }
        }
    });

}

From source file:gov.wa.wsdot.mobile.client.activities.socialmedia.blogger.BlogActivity.java

License:Open Source License

private void createBlogList(final BlogView view) {
    blogItems.clear();/*from   w  w  w. j a v  a  2s  . c  o m*/
    view.showProgressIndicator();
    JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
    // Set timeout for 30 seconds (30000 milliseconds)
    jsonp.setTimeout(30000);
    jsonp.requestObject(BLOG_FEED_URL, new AsyncCallback<BlogFeed>() {

        @Override
        public void onFailure(Throwable caught) {
            view.hideProgressIndicator();
            phoneGap.getNotification().alert("Can't load data. Check your connection.", new AlertCallback() {
                @Override
                public void onOkButtonClicked() {
                    // TODO Auto-generated method stub
                }
            }, "Connection Error");
        }

        @Override
        public void onSuccess(BlogFeed result) {
            BlogItem item = null;

            if (result.getFeed() != null) {
                int numEntries = result.getFeed().getEntry().length();
                for (int i = 0; i < numEntries; i++) {
                    item = new BlogItem();

                    item.setTitle(result.getFeed().getEntry().get(i).getTitle().getT());
                    item.setContent(result.getFeed().getEntry().get(i).getContent().getT());
                    item.setDescription("");
                    item.setImageUrl("");
                    item.setPublished(result.getFeed().getEntry().get(i).getPublished().getT());
                    item.setLink(result.getFeed().getEntry().get(i).getLink().get(4).getHref());

                    blogItems.add(item);
                }

                view.hideProgressIndicator();
                view.render(blogItems);
                view.refresh();
                accessibility.postScreenChangeNotification();
            }

        }
    });

}

From source file:gov.wa.wsdot.mobile.client.activities.socialmedia.facebook.FacebookActivity.java

License:Open Source License

private void createPostList(final FacebookView view) {
    facebookItems.clear();// w ww .  jav a2s  .  c o m
    view.showProgressIndicator();
    JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
    // Set timeout for 30 seconds (30000 milliseconds)
    jsonp.setTimeout(30000);
    jsonp.requestObject(FACEBOOK_FEED_URL, new AsyncCallback<FacebookFeed>() {

        @Override
        public void onFailure(Throwable caught) {
            view.hideProgressIndicator();
            phoneGap.getNotification().alert("Can't load data. Check your connection.", new AlertCallback() {
                @Override
                public void onOkButtonClicked() {
                    // TODO Auto-generated method stub
                }
            }, "Connection Error");
        }

        @Override
        public void onSuccess(FacebookFeed result) {
            FacebookItem item = null;
            //String urlPattern = "(https?:\\/\\/[-a-zA-Z0-9._~:\\/?#@!$&\'()*+,;=%]+)";
            String text;
            //String htmlText;

            if (result.getPosts() != null) {
                int numEntries = result.getPosts().length();
                for (int i = 0; i < numEntries; i++) {
                    item = new FacebookItem();

                    //htmlText = "";
                    text = result.getPosts().get(i).getMessage();
                    //htmlText = text.replaceAll(urlPattern, "<a href=\"$1\">$1</a>");

                    item.setMessage(text);
                    item.setHtmlFormattedMessage(text);
                    item.setCreatedAt(result.getPosts().get(i).getCreatedAt());
                    item.setId(result.getPosts().get(i).getId());
                    item.setType(result.getPosts().get(i).getType());

                    if (item.getType().equalsIgnoreCase("photo")) {
                        item.setLink(result.getPosts().get(i).getLink());
                    }

                    facebookItems.add(item);
                }

                view.hideProgressIndicator();
                view.render(facebookItems);
                view.refresh();
                accessibility.postScreenChangeNotification();
            }

        }
    });

}

From source file:gov.wa.wsdot.mobile.client.activities.socialmedia.news.NewsActivity.java

License:Open Source License

private void createPostList(final NewsView view) {
    newsItems.clear();/*from w  w w  . j av  a  2  s.  c o m*/
    view.showProgressIndicator();
    JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
    // Set timeout for 30 seconds (30000 milliseconds)
    jsonp.setTimeout(30000);
    jsonp.requestObject(NEWS_FEED_URL, new AsyncCallback<NewsFeed>() {

        @Override
        public void onFailure(Throwable caught) {
            view.hideProgressIndicator();
            phoneGap.getNotification().alert("Can't load data. Check your connection.", new AlertCallback() {
                @Override
                public void onOkButtonClicked() {
                    // TODO Auto-generated method stub
                }
            }, "Connection Error");
        }

        @Override
        public void onSuccess(NewsFeed result) {
            NewsItem item = null;

            if (result.getNews() != null) {
                int numEntries = result.getNews().getItems().length();
                for (int i = 0; i < numEntries; i++) {
                    item = new NewsItem();

                    item.setTitle(result.getNews().getItems().get(i).getTitle());
                    item.setDescription(result.getNews().getItems().get(i).getDescription());
                    item.setLink(result.getNews().getItems().get(i).getLink());

                    Date date = parseDateFormat.parse(result.getNews().getItems().get(i).getPubDate());

                    item.setPubDate(displayDateFormat.format(date));

                    newsItems.add(item);
                }

                view.hideProgressIndicator();
                view.render(newsItems);
                view.refresh();
                accessibility.postScreenChangeNotification();
            }

        }
    });

}

From source file:gov.wa.wsdot.mobile.client.activities.socialmedia.twitter.TwitterActivity.java

License:Open Source License

private void createPostList(final TwitterView view, String screenName) {
    String url;/* www  . ja va  2 s  .  c o  m*/

    if (screenName.equals("all")) {
        url = TWITTER_FEED_URL;
    } else {
        url = TWITTER_FEED_URL + "/" + screenName;
    }

    twitterItems.clear();
    view.showProgressIndicator();
    JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
    // Set timeout for 30 seconds (30000 milliseconds)
    jsonp.setTimeout(30000);
    jsonp.requestObject(url, new AsyncCallback<TwitterFeed>() {

        @Override
        public void onFailure(Throwable caught) {
            view.hideProgressIndicator();
            phoneGap.getNotification().alert("Can't load data. Check your connection.", new AlertCallback() {
                @Override
                public void onOkButtonClicked() {
                    // TODO Auto-generated method stub
                }
            }, "Connection Error");
        }

        @Override
        public void onSuccess(TwitterFeed result) {
            TwitterItem item = null;
            //String urlPattern = "(https?:\\/\\/[-a-zA-Z0-9._~:\\/?#@!$&\'()*+,;=%]+)";
            //String atPattern = "@+([_a-zA-Z0-9-]+)";
            //String hashPattern = "#+([_a-zA-Z0-9-]+)";
            String text;
            //String htmlText;

            if (result.getPosts() != null) {
                int numEntries = result.getPosts().length();
                for (int i = 0; i < numEntries; i++) {
                    item = new TwitterItem();

                    //htmlText = "";
                    text = result.getPosts().get(i).getText();
                    //htmlText = text.replaceAll(urlPattern, "<a href=\"$1\">$1</a>");
                    //htmlText = htmlText.replaceAll(atPattern, "<a href=\"http://twitter.com/#!/$1\">@$1</a>");
                    //htmlText = htmlText.replaceAll(hashPattern, "<a href=\"http://twitter.com/#!/search?q=%23$1\">#$1</a>");

                    item.setText(text);
                    item.setId(result.getPosts().get(i).getId());
                    item.setFormatedHtmlText(text);
                    item.setScreenName(result.getPosts().get(i).getUser().getScreenName());
                    item.setCreatedAt(result.getPosts().get(i).getCreatedAt());

                    item.setUserName(result.getPosts().get(i).getUser().getName());
                    item.setProfileImage(
                            twitterProfileImages.get(result.getPosts().get(i).getUser().getScreenName()));

                    JsArray<Media> media = result.getPosts().get(i).getEntities().getMedia();
                    if (media != null) {
                        item.setMediaUrl(
                                result.getPosts().get(i).getEntities().getMedia().get(0).getMediaUrl());
                    }

                    if (item.getMediaUrl() == null) {
                        JsArray<Urls> urls = result.getPosts().get(i).getEntities().getUrls();
                        if (urls != null) {
                            if (result.getPosts().get(i).getEntities().getUrls().get(0) != null) {
                                String expandedUrl = result.getPosts().get(i).getEntities().getUrls().get(0)
                                        .getExpandedUrl();
                                if (expandedUrl.matches("(.*)twitpic.com(.*)")) {
                                    item.setMediaUrl(expandedUrl);
                                }
                            }
                        }
                    }

                    if (item.getMediaUrl() == null) {
                        item.setMediaUrl("");
                    }

                    twitterItems.add(item);
                }

                view.hideProgressIndicator();
                view.render(twitterItems);
                view.refresh();
                accessibility.postScreenChangeNotification();
            }

        }
    });

}

From source file:gov.wa.wsdot.mobile.client.activities.socialmedia.youtube.YouTubeActivity.java

License:Open Source License

private void createPostList(final YouTubeView view) {
    youTubeItems.clear();//from  w  w  w  .ja  v a  2s  . c om
    view.showProgressIndicator();
    JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
    // Set timeout for 30 seconds (30000 milliseconds)
    jsonp.setTimeout(30000);
    jsonp.requestObject(YOUTUBE_FEED_URL, new AsyncCallback<YouTubeFeed>() {
        @Override
        public void onFailure(Throwable caught) {
            view.hideProgressIndicator();
            phoneGap.getNotification().alert("Can't load data. Check your connection.", new AlertCallback() {
                @Override
                public void onOkButtonClicked() {
                    // TODO Auto-generated method stub
                }
            }, "Connection Error");
        }

        @Override
        public void onSuccess(YouTubeFeed result) {
            YouTubeItem item = null;

            if (result.getItems() != null) {
                int numEntries = result.getItems().length();
                for (int i = 0; i < numEntries; i++) {
                    // If we don't have a standard sized 640x480 video available, move on
                    if (result.getItems().get(i).getSnippet().getThumbnails().getStandard() == null) {
                        continue;
                    } else {
                        item = new YouTubeItem();

                        item.setId(result.getItems().get(i).getSnippet().getResourceId().getVideoId());
                        item.setTitle(result.getItems().get(i).getSnippet().getTitle());
                        item.setDescription(result.getItems().get(i).getSnippet().getDescription());
                        item.setThumbnailUrl(
                                result.getItems().get(i).getSnippet().getThumbnails().getStandard().getUrl());
                        item.setUploaded(result.getItems().get(i).getSnippet().getPublished());

                        youTubeItems.add(item);
                    }
                }

                view.hideProgressIndicator();
                view.render(youTubeItems);
                view.refresh();
                accessibility.postScreenChangeNotification();
            }

        }
    });

}