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:br.com.viniciuscr.notification2android.mediaPlayer.MusicUtils.java

public static void addToPlaylist(Context context, long[] ids, long playlistid) {
    if (ids == null) {
        // this shouldn't happen (the menuitems shouldn't be visible
        // unless the selected item represents something playable
        Log.e("MusicBase", "ListSelection null");
    } else {//w  w w. j  a v a  2  s.  co  m
        int size = ids.length;
        ContentResolver resolver = context.getContentResolver();
        // need to determine the number of items currently in the playlist,
        // so the play_order field can be maintained.
        String[] cols = new String[] { "count(*)" };
        Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
        Cursor cur = resolver.query(uri, cols, null, null, null);
        cur.moveToFirst();
        int base = cur.getInt(0);
        cur.close();
        int numinserted = 0;
        for (int i = 0; i < size; i += 1000) {
            makeInsertItems(ids, i, 1000, base);
            numinserted += resolver.bulkInsert(uri, sContentValuesCache);
        }
        String message = context.getResources().getQuantityString(R.plurals.NNNtrackstoplaylist, numinserted,
                numinserted);
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        //mLastPlaylistSelected = playlistid;
    }
}

From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*from w ww.  j  a  va 2  s . com*/

    Context context = getContext();

    App.getApiManager().getEarthquakeService().getData().enqueue(new Callback<EarthquakeObject>() {
        @Override
        public void onResponse(Call<EarthquakeObject> call, Response<EarthquakeObject> response) {
            EarthquakeObject earthquake = response.body();

            Vector<ContentValues> cVVector = new Vector<>(earthquake.getFeatures().size());

            double currentBiggest = 0.0;
            ContentValues notifyValues = null;

            for (Feature each : earthquake.getFeatures()) {

                ContentValues earthquakeValues = new ContentValues();

                earthquakeValues.put(EarthquakeColumns.PLACE, each.getProperties().getPlace());
                earthquakeValues.put(EarthquakeColumns.ID_EARTH, each.getId());
                earthquakeValues.put(EarthquakeColumns.MAG, each.getProperties().getMag());
                earthquakeValues.put(EarthquakeColumns.TYPE, each.getProperties().getType());
                earthquakeValues.put(EarthquakeColumns.ALERT, each.getProperties().getAlert());
                earthquakeValues.put(EarthquakeColumns.TIME, each.getProperties().getTime());
                earthquakeValues.put(EarthquakeColumns.URL, each.getProperties().getUrl());
                earthquakeValues.put(EarthquakeColumns.DETAIL, each.getProperties().getDetail());
                earthquakeValues.put(EarthquakeColumns.DEPTH, each.getGeometry().getCoordinates().get(2));
                earthquakeValues.put(EarthquakeColumns.LONGITUDE, each.getGeometry().getCoordinates().get(0));
                earthquakeValues.put(EarthquakeColumns.LATITUDE, each.getGeometry().getCoordinates().get(1));

                LatLng latLng = new LatLng(each.getGeometry().getCoordinates().get(1),
                        each.getGeometry().getCoordinates().get(0));
                LatLng location = LocationUtils.getLocation(context);
                earthquakeValues.put(EarthquakeColumns.DISTANCE, LocationUtils.getDistance(latLng, location));

                cVVector.add(earthquakeValues);

                if (each.getProperties().getMag() != null && each.getProperties().getMag() > currentBiggest) {
                    currentBiggest = each.getProperties().getMag();
                    notifyValues = new ContentValues(earthquakeValues);
                    notifyValues.put(EarthquakeColumns.PLACE,
                            Utilities.formatEarthquakePlace(each.getProperties().getPlace()));
                }
            }

            int inserted = 0;
            // add to database
            ContentResolver resolver = context.getContentResolver();

            if (cVVector.size() > 0) {
                ContentValues[] cvArray = new ContentValues[cVVector.size()];
                cVVector.toArray(cvArray);
                inserted = resolver.bulkInsert(EarthquakeColumns.CONTENT_URI, cvArray);
            }

            // Set the date to day minus one to delete old data from the database
            Date date = new Date();
            date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS);

            int deleted = resolver.delete(EarthquakeColumns.CONTENT_URI, EarthquakeColumns.TIME + " <= ?",
                    new String[] { String.valueOf(date.getTime()) });
            Log.v(TAG, "Service Complete. " + inserted + " Inserted, " + deleted + " deleted");
            sendNotification(notifyValues);
        }

        @Override
        public void onFailure(Call<EarthquakeObject> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.toString());
        }
    });

    App.getNewsManager().getNewsService().getNews().enqueue(new Callback<Rss>() {
        @Override
        public void onResponse(Call<Rss> call, Response<Rss> response) {
            Channel news = response.body().getChannel();

            Vector<ContentValues> cVVector = new Vector<>(news.getItem().size());

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z",
                    Locale.getDefault());
            Date date = new Date();

            for (Item each : news.getItem()) {

                ContentValues weatherValues = new ContentValues();

                try {
                    date = simpleDateFormat.parse(each.getPubDate());
                } catch (ParseException e) {
                    Log.e(TAG, "e:" + e);
                }

                weatherValues.put(NewsColumns.DATE, date.getTime());
                weatherValues.put(NewsColumns.TITLE, each.getTitle());
                weatherValues.put(NewsColumns.DESCRIPTION,
                        Html.toHtml(new SpannedString(each.getDescription())));
                weatherValues.put(NewsColumns.URL, each.getLink());
                weatherValues.put(NewsColumns.GUID, each.getGuid().getContent());

                cVVector.add(weatherValues);
            }

            int inserted = 0;
            // add to database
            ContentResolver resolver = getContext().getContentResolver();

            if (cVVector.size() > 0) {

                // Student: call bulkInsert to add the weatherEntries to the database here
                ContentValues[] cvArray = new ContentValues[cVVector.size()];
                cVVector.toArray(cvArray);
                inserted = resolver.bulkInsert(NewsColumns.CONTENT_URI, cvArray);
            }

            // Set the date to day minus two to delete old data from the database
            date = new Date();
            date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS * 3);

            int deleted = resolver.delete(NewsColumns.CONTENT_URI, NewsColumns.DATE + " <= ?",
                    new String[] { String.valueOf(date.getTime()) });
        }

        @Override
        public void onFailure(Call<Rss> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.toString());
        }
    });

    // TODO: 4/22/16 possible refactoring 
    //checking the last update and notify if it' the first of the day
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String lastNotificationKey = context.getString(R.string.sharedprefs_key_last_countupdate);
    long lastSync = prefs.getLong(lastNotificationKey, DateUtils.DAY_IN_MILLIS);

    if (System.currentTimeMillis() - lastSync >= Utilities.getSyncIntervalPrefs(context)
            * DateUtils.SECOND_IN_MILLIS) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        Date date = new Date(System.currentTimeMillis());

        String startTime[] = new String[] { simpleDateFormat.format(date.getTime() - DateUtils.YEAR_IN_MILLIS),
                simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS * 30),
                simpleDateFormat.format(date.getTime() - DateUtils.WEEK_IN_MILLIS),
                simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS) };

        String endTime = simpleDateFormat.format(date);

        int iterator = 1;
        while (iterator < CountColumns.ALL_COLUMNS.length) {
            final int round = iterator;

            App.getApiManager().getEarthquakeService().getEarthquakeStats(startTime[round - 1], endTime)
                    .enqueue(new Callback<CountEarthquakes>() {
                        @Override
                        public void onResponse(Call<CountEarthquakes> call,
                                Response<CountEarthquakes> response) {
                            ContentValues count = new ContentValues();
                            count.put(CountColumns.ALL_COLUMNS[round], response.body().getCount());

                            ContentResolver contentResolver = context.getContentResolver();

                            Cursor cursor = contentResolver.query(CountColumns.CONTENT_URI, null, null, null,
                                    null);

                            if (cursor != null) {
                                if (cursor.getCount() < 1) {
                                    long inserted = ContentUris
                                            .parseId(contentResolver.insert(CountColumns.CONTENT_URI, count));
                                    //Log.d(TAG, "inserted:" + inserted);
                                } else {
                                    int updated = contentResolver.update(CountColumns.CONTENT_URI, count,
                                            CountColumns._ID + " = ?", new String[] { "1" });
                                    //Log.d(TAG, "updated: " + updated);
                                }
                                cursor.close();
                            }

                        }

                        @Override
                        public void onFailure(Call<CountEarthquakes> call, Throwable t) {
                            Log.e(TAG, "Error: " + t);
                        }
                    });
            iterator++;
        }

        //refreshing last sync
        prefs.edit().putLong(lastNotificationKey, System.currentTimeMillis()).apply();
    }

    // notify PagerActivity that data has been updated
    context.getContentResolver().notifyChange(EarthquakeColumns.CONTENT_URI, null, false);
    context.getContentResolver().notifyChange(NewsColumns.CONTENT_URI, null, false);
    context.getContentResolver().notifyChange(CountColumns.CONTENT_URI, null, false);

    updateWidgets();
}

From source file:no.uka.findmyapp.android.rest.client.RestProcessor.java

/**
 * Send to content provider./*from   w ww  . j  a va 2s.  c o m*/
 *
 * @param uri the uri
 * @param object the object
 * @param returnType the return type
 */
private void sendToContentProvider(Uri uri, Serializable object, String returnType) {
    Log.v(debug, "sendToContentProvider: serializable object " + object.getClass().getName());

    ContentResolver cr = mContext.getContentResolver();

    if (object instanceof List) {

        Class theClass = null;
        try {
            theClass = Class.forName(returnType);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        List<ContentValues> list = ContentHelper.getContentValuesList(object, theClass);
        Log.v(debug, "parsing contentvalue array");
        ContentValues[] cva = new ContentValues[list.size()];
        for (ContentValues cv : list) {
            cva[list.indexOf(cv)] = cv;
        }
        Log.v(debug, cva.toString());
        cr.bulkInsert(UkaEventContract.EVENT_CONTENT_URI, cva);
    } else {
        ContentValues cv = new ContentValues(ContentHelper.getContentValues(object));
        cr.insert(uri, cv);
    }
}

From source file:org.projectbuendia.client.ui.OdkActivityLauncher.java

/**
 * Caches the observation changes locally for a given patient.
 *//*from  w  w w  .ja v a2 s.com*/
private static void updateObservationCache(String patientUuid, TreeElement savedRoot,
        ContentResolver resolver) {
    ContentValues common = new ContentValues();
    // It's critical that UUID is {@code null} for temporary observations, so we make it
    // explicit here. See {@link Contracts.Observations.UUID} for details.
    common.put(Contracts.Observations.UUID, (String) null);
    common.put(Contracts.Observations.PATIENT_UUID, patientUuid);

    final DateTime encounterTime = getEncounterAnswerDateTime(savedRoot);
    if (encounterTime == null)
        return;
    common.put(Contracts.Observations.ENCOUNTER_MILLIS, encounterTime.getMillis());
    common.put(Contracts.Observations.ENCOUNTER_UUID, UUID.randomUUID().toString());

    Set<Integer> xformConceptIds = new HashSet<>();
    List<ContentValues> toInsert = getAnsweredObservations(common, savedRoot, xformConceptIds);
    Map<String, String> xformIdToUuid = mapFormConceptIdToUuid(xformConceptIds, resolver);

    // Remap concept ids to uuids, skipping anything we can't remap.
    for (Iterator<ContentValues> i = toInsert.iterator(); i.hasNext();) {
        ContentValues values = i.next();
        if (!mapIdToUuid(xformIdToUuid, values, Contracts.Observations.CONCEPT_UUID)) {
            i.remove();
        }
        mapIdToUuid(xformIdToUuid, values, Contracts.Observations.VALUE);
    }

    resolver.bulkInsert(Contracts.Observations.CONTENT_URI,
            toInsert.toArray(new ContentValues[toInsert.size()]));
}

From source file:com.andrew.apollo.utils.MusicUtils.java

/**
 * @param context The {@link Context} to use.
 * @param ids The id of the song(s) to add.
 * @param playlistid The id of the playlist being added to.
 *///from  w  w  w.  j  a v a  2 s .c  o  m
public static void addToPlaylist(final Context context, final long[] ids, final long playlistid) {
    if (ids == null) {
        LOG.warn("song ids given null, not adding anything to playlist.");
        return;
    }

    if (ids == sEmptyList) {
        LOG.warn("song ids was empty, not adding anything to playlist.");
        return;
    }

    final int size = ids.length;
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[] { "count(*)" };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
    Cursor cursor = null;
    try {
        cursor = resolver.query(uri, projection, null, null, null);
    } catch (Throwable ignored) {
    }

    if (cursor != null) {
        cursor.moveToFirst();
        final int base = cursor.getInt(0);
        cursor.close();
        int numinserted = 0;
        for (int offSet = 0; offSet < size; offSet += 1000) {
            makeInsertItems(ids, offSet, 1000, base);
            numinserted += resolver.bulkInsert(uri, mContentValuesCache);
        }
        final String message = context.getResources().getQuantityString(R.plurals.NNNtrackstoplaylist,
                numinserted, numinserted);
        AppMsg.makeText(context, message, AppMsg.STYLE_CONFIRM).show();
        refresh();
    } else {
        LOG.warn("Unable to complete addToPlaylist, review the logic");
    }
}

From source file:com.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java

/**
 * Parses and stores the JSON data in the TMDbContentProvider
 * @param dataJSON The JSON data from server
 * @param type Flag for the try of movie to fetch.  Should match flag used in fetchMovies
 * @throws JSONException//from   ww  w.  j a v  a2  s  .  c  o m
 */
private static int[] storeJsonMovies(String dataJSON, int type, Context context) throws JSONException {
    //TODO use ContentProviderClient instead of ContentResolver
    try {
        JSONObject moviesJSON = new JSONObject(dataJSON);
        JSONArray results = moviesJSON.getJSONArray("results");
        final int resultLength = results.length();
        ContentValues[] contentValues = new ContentValues[resultLength];
        int[] ids = new int[resultLength];
        int isPopular;
        int isTopRated;
        int isFavorite;

        switch (type) {
        case MOVIES_POPULAR:
            isPopular = 1;
            isTopRated = 0;
            break;
        case MOVIES_TOP_RATED:
            isPopular = 0;
            isTopRated = 1;
            break;
        default:
            isPopular = 0;
            isTopRated = 0;
        }
        Cursor cursor = getFavoriteIds(context);
        ContentResolver contentResolver = context.getContentResolver();

        for (int i = 0; i < resultLength; i++) {
            JSONObject movie = results.getJSONObject(i);
            contentValues[i] = new ContentValues();
            contentValues[i].put(TMDbContract.Movies.ORIGINAL_TITLE,
                    movie.getString(TMDbContract.Movies.ORIGINAL_TITLE));

            contentValues[i].put(TMDbContract.Movies.OVERVIEW, movie.getString(TMDbContract.Movies.OVERVIEW));
            contentValues[i].put(TMDbContract.Movies.POSTER, movie.getString(TMDbContract.Movies.POSTER));
            contentValues[i].put(TMDbContract.Movies.RELEASE_DATE,
                    movie.getString(TMDbContract.Movies.RELEASE_DATE));
            contentValues[i].put(TMDbContract.Movies.POPULARITY,
                    movie.getDouble(TMDbContract.Movies.POPULARITY));
            contentValues[i].put(TMDbContract.Movies.VOTE_AVERAGE,
                    movie.getDouble(TMDbContract.Movies.VOTE_AVERAGE));

            int moveId = movie.getInt(TMDbContract.Movies.MOVIE_ID);
            contentValues[i].put(TMDbContract.Movies.MOVIE_ID, moveId);
            cursor.moveToPosition(-1);
            while (cursor.moveToNext()) {
                int favoriteId = cursor.getInt(cursor.getColumnIndex(TMDbContract.Movies.MOVIE_ID));
                if (favoriteId == moveId) {
                    deleteFavorite(context, moveId);
                    isFavorite = 1;
                    contentValues[i].put(TMDbContract.Movies.IS_FAVORITE, isFavorite);
                    break;
                }
            }

            //TODO read up on how to have the col initialized to 0 by defualt
            contentValues[i].put(TMDbContract.Movies.IS_POPULAR, isPopular);
            contentValues[i].put(TMDbContract.Movies.IS_TOP_RATED, isTopRated);

            ids[i] = movie.getInt(TMDbContract.Movies.MOVIE_ID);
        }

        int numInserted = contentResolver.bulkInsert(TMDbContract.Movies.URI, contentValues);

        if (numInserted != resultLength) {
            Log.e(TAG, "Not all of the result were inserted.\n Amount inserted: " + numInserted
                    + "\nAmount from server: " + resultLength);
        }

        return ids;
    } catch (JSONException e) {
        Log.d(TAG, e.getMessage(), e);
        e.printStackTrace();
        return null;
    }
}

From source file:com.metinkale.prayerapp.MainIntentService.java

private void handleCalendarIntegration() {
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        Prefs.setCalendar("-1");
        return;//from  ww w .j a va 2  s  .c o  m
    }
    Context context = App.getContext();
    try {
        ContentResolver cr = context.getContentResolver();

        cr.delete(CalendarContract.Events.CONTENT_URI,
                CalendarContract.Events.DESCRIPTION + "=\"com.metinkale.prayer\"", null);

        String id = Prefs.getCalendar();

        if ("-1".equals(id) || (Prefs.getLanguage() == null)) {
            return;
        }
        int year = LocalDate.now().getYear();
        Collection<int[]> days = new ArrayList<>();
        days.addAll(HicriDate.getHolydays(year));
        days.addAll(HicriDate.getHolydays(year + 1));

        int i = 0;
        ContentValues[] events = new ContentValues[days.size()];
        for (int[] date : days) {
            ContentValues event = new ContentValues();

            event.put(CalendarContract.Events.CALENDAR_ID, id);
            event.put(CalendarContract.Events.TITLE, Utils.getHolyday(date[HicriDate.DAY] - 1));
            event.put(CalendarContract.Events.DESCRIPTION, "com.metinkale.prayer");

            ReadableInstant cal = new DateTime(date[HicriDate.GY], date[HicriDate.GM], date[HicriDate.GD], 0, 0,
                    0);

            long dtstart = cal.getMillis();
            long dtend = dtstart + DateUtils.DAY_IN_MILLIS;

            event.put(CalendarContract.Events.DTSTART, dtstart + TimeZone.getDefault().getOffset(dtstart));
            event.put(CalendarContract.Events.DTEND, dtend + TimeZone.getDefault().getOffset(dtend));
            event.put(CalendarContract.Events.EVENT_TIMEZONE, Time.TIMEZONE_UTC);
            event.put(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CONFIRMED);
            event.put(CalendarContract.Events.ALL_DAY, 1);

            events[i] = event;
            i++;
        }
        cr.bulkInsert(CalendarContract.Events.CONTENT_URI, events);
    } catch (Exception e) {
        Prefs.setCalendar("-1");
        Crashlytics.logException(e);
    }
}

From source file:com.appsimobile.appsii.module.weather.WeatherLoadingService.java

void onWeatherDataLoaded(@Nullable CircularArray<WeatherData> weatherDataList, String unit) {

    int N = weatherDataList == null ? 0 : weatherDataList.size();
    for (int i1 = 0; i1 < N; i1++) {
        WeatherData weatherData = weatherDataList.get(i1);

        ContentValues weatherValues = new ContentValues();

        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_LAST_UPDATED, System.currentTimeMillis());
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_WOEID, weatherData.woeid);

        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_ATMOSPHERE_HUMIDITY,
                weatherData.atmosphereHumidity);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_ATMOSPHERE_PRESSURE,
                weatherData.atmospherePressure);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_ATMOSPHERE_RISING,
                weatherData.atmosphereRising);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_ATMOSPHERE_VISIBILITY,
                weatherData.atmosphereVisible);

        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_NOW_CONDITION_CODE,
                weatherData.nowConditionCode);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_NOW_TEMPERATURE,
                weatherData.nowTemperature);

        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_SUNRISE, weatherData.sunrise);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_SUNSET, weatherData.sunset);

        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_WIND_CHILL, weatherData.windChill);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_WIND_DIRECTION, weatherData.windDirection);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_WIND_SPEED, weatherData.windSpeed);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_CITY, weatherData.location);
        weatherValues.put(WeatherContract.WeatherColumns.COLUMN_NAME_UNIT, unit);

        ContentResolver contentResolver = mContext.getContentResolver();
        contentResolver.insert(WeatherContract.WeatherColumns.CONTENT_URI, weatherValues);

        List<WeatherData.Forecast> forecasts = weatherData.forecasts;
        if (!forecasts.isEmpty()) {

            int count = forecasts.size();
            ContentValues[] forecastValues = new ContentValues[count];

            for (int i = 0; i < count; i++) {
                WeatherData.Forecast forecast = forecasts.get(i);

                ContentValues contentValues = new ContentValues();
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_FORECAST_DAY, forecast.julianDay);
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_LAST_UPDATED,
                        System.currentTimeMillis());
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_LOCATION_WOEID,
                        weatherData.woeid);
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_CONDITION_CODE,
                        forecast.conditionCode);
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_TEMPERATURE_HIGH, forecast.high);
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_TEMPERATURE_LOW, forecast.low);
                contentValues.put(WeatherContract.ForecastColumns.COLUMN_NAME_UNIT, unit);
                forecastValues[i] = contentValues;
            }//from w  w w  .ja  v  a2 s . c  om
            Uri uri = WeatherContract.ForecastColumns.CONTENT_URI;
            contentResolver.bulkInsert(uri, forecastValues);
        }
    }

    Intent i = new Intent(ACTION_WEATHER_UPDATED);
    i.setPackage(mContext.getPackageName());
    mContext.sendBroadcast(i);
}

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

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

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

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

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

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

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

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

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

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

        if (newCvs.size() > 0) {
            ContentValues[] cvs = new ContentValues[newCvs.size()];
            newCvs.toArray(cvs);//www  .  j  a  v  a2  s.  co  m

            cr.bulkInsert(Friends.CONTENT_URI, cvs);

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

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

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

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

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

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

    /** 
     * Check the cache table for the last time data was downloaded. If we are within
     * the allowed time period, don't sync, otherwise get fresh data from the server.
     */
    try {
        cursor = resolver.query(Caches.CONTENT_URI, new String[] { Caches.CACHE_LAST_UPDATED },
                Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "border_wait" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS;
            //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min");
            shouldUpdate = (Math.abs(now - lastUpdated) > (15 * DateUtils.MINUTE_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

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

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

        starred = getStarred();

        try {
            URL url = new URL(BORDER_WAIT_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("waittimes");
            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(BorderWait.BORDER_WAIT_ID, item.getInt("id"));
                timesValues.put(BorderWait.BORDER_WAIT_TITLE, item.getString("name"));
                timesValues.put(BorderWait.BORDER_WAIT_UPDATED, item.getString("updated"));
                timesValues.put(BorderWait.BORDER_WAIT_LANE, item.getString("lane"));
                timesValues.put(BorderWait.BORDER_WAIT_ROUTE, item.getInt("route"));
                timesValues.put(BorderWait.BORDER_WAIT_DIRECTION, item.getString("direction"));
                timesValues.put(BorderWait.BORDER_WAIT_TIME, item.getInt("wait"));

                if (starred.contains(item.getInt("id"))) {
                    timesValues.put(BorderWait.BORDER_WAIT_IS_STARRED, 1);
                }

                times.add(timesValues);

            }

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

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

}