Example usage for android.content ContentResolver bulkInsert

List of usage examples for android.content ContentResolver bulkInsert

Introduction

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

Prototype

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

Source Link

Document

Inserts multiple rows into a table at the given URL.

Usage

From source file:com.example.android.sunshine.sync.SunshineSyncTask.java

/**
 * Performs the network request for updated weather, parses the JSON from that request, and
 * inserts the new weather information into our ContentProvider. Will notify the user that new
 * weather has been loaded if the user hasn't been notified of the weather within the last day
 * AND they haven't disabled notifications in the preferences screen.
 *
 * @param context Used to access utility methods and the ContentResolver
 *//*from  ww  w .j a  v  a2  s .c om*/
synchronized public static void syncWeather(Context context) {

    try {
        /*
         * The getUrl method will return the URL that we need to get the forecast JSON for the
         * weather. It will decide whether to create a URL based off of the latitude and
         * longitude or off of a simple location as a String.
         */
        URL weatherRequestUrl = NetworkUtils.getUrl(context);

        /* Use the URL to retrieve the JSON */
        String jsonWeatherResponse = NetworkUtils.getResponseFromHttpUrl(weatherRequestUrl);

        /* Parse the JSON into a list of weather values */
        ContentValues[] weatherValues = OpenWeatherJsonUtils.getWeatherContentValuesFromJson(context,
                jsonWeatherResponse);

        /*
         * In cases where our JSON contained an error code, getWeatherContentValuesFromJson
         * would have returned null. We need to check for those cases here to prevent any
         * NullPointerExceptions being thrown. We also have no reason to insert fresh data if
         * there isn't any to insert.
         */
        if (weatherValues != null && weatherValues.length != 0) {
            /* Get a handle on the ContentResolver to delete and insert data */
            ContentResolver sunshineContentResolver = context.getContentResolver();

            /* Delete old weather data because we don't need to keep multiple days' data */
            sunshineContentResolver.delete(WeatherContract.WeatherEntry.CONTENT_URI, null, null);

            /* Insert our new weather data into Sunshine's ContentProvider */
            sunshineContentResolver.bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, weatherValues);

            /*
             * Finally, after we insert data into the ContentProvider, determine whether or not
             * we should notify the user that the weather has been refreshed.
             */
            boolean notificationsEnabled = SunshinePreferences.areNotificationsEnabled(context);

            /*
             * If the last notification was shown was more than 1 day ago, we want to send
             * another notification to the user that the weather has been updated. Remember,
             * it's important that you shouldn't spam your users with notifications.
             */
            long timeSinceLastNotification = SunshinePreferences.getEllapsedTimeSinceLastNotification(context);

            boolean oneDayPassedSinceLastNotification = false;

            if (timeSinceLastNotification >= DateUtils.DAY_IN_MILLIS) {
                oneDayPassedSinceLastNotification = true;
            }

            /*
             * We only want to show the notification if the user wants them shown and we
             * haven't shown a notification in the past day.
             */
            if (notificationsEnabled && oneDayPassedSinceLastNotification) {
                NotificationUtils.notifyUserOfNewWeather(context);
            }

            /* If the code reaches this point, we have successfully performed our sync */

        }

    } catch (Exception e) {
        /* Server probably invalid */
        e.printStackTrace();
    }

    // Sync new weather data to Android Wear
    sendWearWeatherData(context);

}

From source file:com.example.igorklimov.popularmoviesdemo.helpers.Utility.java

public static void addDetails(ContentValues details, ArrayList<ContentValues> allReviews, Context context) {
    ContentResolver resolver = context.getContentResolver();

    ContentValues[] a = new ContentValues[allReviews.size()];
    allReviews.toArray(a);/*  w  w  w  . jav  a  2  s.co m*/

    Log.v(TAG, "addDetails: " + resolver.insert(MovieContract.Details.CONTENT_URI, details));
    Log.v(TAG, "addDetails: " + resolver.bulkInsert(MovieContract.Review.CONTENT_URI, a));
}

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

/**
 * Parses and stores the JSON data in the TMDbContentProvider
 * @param jsonDataArray An array of raw JSON strings
 * @throws JSONException/*from www.  j ava  2s  .  co  m*/
 */
private static void storeJsonReviews(String[] jsonDataArray, Context context) throws JSONException {
    ArrayList<ContentValues> contentValuesArrayList = new ArrayList<ContentValues>(40);

    for (String dataJSON : jsonDataArray) {
        try {
            JSONObject reviewsJSON = new JSONObject(dataJSON);
            JSONArray results = reviewsJSON.getJSONArray("results");
            int movieId = reviewsJSON.getInt(TMDbContract.Movies.MOVIE_ID);
            int resultLength = results.length();

            ContentValues value;

            for (int i = 0; i < resultLength; i++) {
                JSONObject movie = results.getJSONObject(i);
                value = new ContentValues();
                value.put(TMDbContract.Reviews.AUTHOR, movie.getString(TMDbContract.Reviews.AUTHOR));
                value.put(TMDbContract.Reviews.REVIEW_CONTENT,
                        movie.getString(TMDbContract.Reviews.REVIEW_CONTENT));
                value.put(TMDbContract.Reviews.REVIEW_ID, movie.getString(TMDbContract.Reviews.REVIEW_ID));
                value.put(TMDbContract.Reviews.MOVIE_IDS, movieId);
                contentValuesArrayList.add(value);
            }
        } catch (JSONException e) {
            Log.d(TAG, e.getMessage(), e);
            e.printStackTrace();
        }
    }
    ContentResolver contentResolver = context.getContentResolver();
    ContentValues[] contentValues = new ContentValues[contentValuesArrayList.size()];
    contentValues = contentValuesArrayList.toArray(contentValues);

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

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

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

/**
 * Parses and stores the JSON data in the TMDbContentProvider
 * @param jsonDataArray An array of raw JSON strings
 * @throws JSONException//from w w w .j ava2s .c o m
 */
private static void storeJsonVideos(String[] jsonDataArray, Context context) throws JSONException {
    ArrayList<ContentValues> contentValuesArrayList = new ArrayList<ContentValues>(40);

    for (String dataJSON : jsonDataArray) {
        try {
            JSONObject videosJSON = new JSONObject(dataJSON);
            JSONArray results = videosJSON.getJSONArray("results");
            int movieId = videosJSON.getInt(TMDbContract.Movies.MOVIE_ID);
            int resultLength = results.length();
            ContentValues values;

            for (int i = 0; i < resultLength; i++) {
                JSONObject video = results.getJSONObject(i);
                values = new ContentValues();

                values.put(TMDbContract.Videos.NAME, video.getString(TMDbContract.Videos.NAME));
                values.put(TMDbContract.Videos.KEY, video.getString(TMDbContract.Videos.KEY));
                //TODO check what type of video and store the associated value (see contract)
                values.put(TMDbContract.Videos.TYPE, 0);
                values.put(TMDbContract.Videos.VIDEO_ID, video.getString(TMDbContract.Videos.VIDEO_ID));
                values.put(TMDbContract.Videos.MOVIE_IDS, movieId);

                String printdata = video.getString(TMDbContract.Videos.VIDEO_ID);
                Log.d(TAG, "videoID " + printdata);
                contentValuesArrayList.add(values);
            }
        } catch (JSONException e) {
            Log.d(TAG, e.getMessage(), e);
            e.printStackTrace();
        }
    }

    ContentResolver contentResolver = context.getContentResolver();
    ContentValues[] contentValues = new ContentValues[contentValuesArrayList.size()];
    contentValues = contentValuesArrayList.toArray(contentValues);

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

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

From source file:gxu.software_engineering.market.android.util.ServiceHelper.java

public static void doing(ContentResolver contentResolver, Intent intent) throws JSONException {
    String httpUri = intent.getStringExtra(C.HTTP_URI);
    Log.i("http uri", httpUri);
    JSONObject data = null;/*from ww w.j a va 2s . c  o m*/
    try {
        data = RESTMethod.get(httpUri);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.i("json result", data.toString());
    JSONArray array = null;
    ContentValues[] items = null;
    switch (intent.getIntExtra(C.TARGET_ENTITY, -1)) {
    case CATEGORIES:
        array = data.getJSONArray(C.CATEGORIES);
        ContentValues[] categories = Processor.toCategories(array);
        contentResolver.bulkInsert(intent.getData(), categories);
        break;
    case LASTEST_USERS:
        array = data.getJSONArray(C.USERS);
        ContentValues[] users = Processor.toUsers(array);
        contentResolver.bulkInsert(intent.getData(), users);
        break;
    case LASTEST_ITEMS:
        array = data.getJSONArray(C.ITEMS);
        items = Processor.toItems(array);
        contentResolver.bulkInsert(intent.getData(), items);
        break;
    case HOTTEST_ITEMS:
        array = data.getJSONArray(C.ITEMS);
        items = Processor.toItems(array);
        contentResolver.bulkInsert(intent.getData(), items);
        break;
    case USER_ITEMS:
        array = data.getJSONArray(C.ITEMS);
        items = Processor.toItems(array);
        contentResolver.bulkInsert(intent.getData(), items);
        break;
    case CATEGORY_ITEMS:
        array = data.getJSONArray(C.ITEMS);
        items = Processor.toItems(array);
        contentResolver.bulkInsert(intent.getData(), items);
        break;
    case USER_CLOSED_ITEMS:
        array = data.getJSONArray(C.ITEMS);
        items = Processor.toItems(array);
        contentResolver.bulkInsert(intent.getData(), items);
        break;
    case USER_DEAL_ITEMS:
        array = data.getJSONArray(C.ITEMS);
        items = Processor.toItems(array);
        contentResolver.bulkInsert(intent.getData(), items);
        break;
    default:
        throw new IllegalArgumentException("sorry, 404 for the target!");
    }
}

From source file:info.guardianproject.otr.app.im.app.DatabaseUtils.java

/** Insert the plugin settings into the database. */
private static int saveProviderSettings(ContentResolver cr, long providerId, Map<String, String> config) {
    ContentValues[] settingValues = new ContentValues[config.size()];
    int index = 0;
    for (Map.Entry<String, String> entry : config.entrySet()) {
        ContentValues settingValue = new ContentValues();
        settingValue.put(Imps.ProviderSettings.PROVIDER, providerId);
        settingValue.put(Imps.ProviderSettings.NAME, entry.getKey());
        settingValue.put(Imps.ProviderSettings.VALUE, entry.getValue());
        settingValues[index++] = settingValue;
    }/*  w w w  . j  a va  2s . c  o  m*/
    return cr.bulkInsert(Imps.ProviderSettings.CONTENT_URI, settingValues);
}

From source file:com.mutu.gpstracker.breadcrumbs.DownloadBreadcrumbsTrackTask.java

@Override
protected void onPostExecute(Uri result) {
    super.onPostExecute(result);

    long ogtTrackId = Long.parseLong(result.getLastPathSegment());
    Uri metadataUri = Uri.withAppendedPath(ContentUris.withAppendedId(Tracks.CONTENT_URI, ogtTrackId),
            "metadata");

    BreadcrumbsTracks tracks = mAdapter.getBreadcrumbsTracks();
    Integer bcTrackId = mTrack.second;
    Integer bcBundleId = tracks.getBundleIdForTrackId(bcTrackId);
    //TODO Integer bcActivityId = tracks.getActivityIdForBundleId(bcBundleId);
    String bcDifficulty = tracks.getValueForItem(mTrack, BreadcrumbsTracks.DIFFICULTY);
    String bcRating = tracks.getValueForItem(mTrack, BreadcrumbsTracks.RATING);
    String bcPublic = tracks.getValueForItem(mTrack, BreadcrumbsTracks.ISPUBLIC);
    String bcDescription = tracks.getValueForItem(mTrack, BreadcrumbsTracks.DESCRIPTION);

    ArrayList<ContentValues> metaValues = new ArrayList<ContentValues>();
    if (bcTrackId != null) {
        metaValues.add(buildContentValues(BreadcrumbsTracks.TRACK_ID, Long.toString(bcTrackId)));
    }/*w  w  w .ja v  a  2 s.co  m*/
    if (bcDescription != null) {
        metaValues.add(buildContentValues(BreadcrumbsTracks.DESCRIPTION, bcDescription));
    }
    if (bcDifficulty != null) {
        metaValues.add(buildContentValues(BreadcrumbsTracks.DIFFICULTY, bcDifficulty));
    }
    if (bcRating != null) {
        metaValues.add(buildContentValues(BreadcrumbsTracks.RATING, bcRating));
    }
    if (bcPublic != null) {
        metaValues.add(buildContentValues(BreadcrumbsTracks.ISPUBLIC, bcPublic));
    }
    if (bcBundleId != null) {
        metaValues.add(buildContentValues(BreadcrumbsTracks.BUNDLE_ID, Integer.toString(bcBundleId)));
    }
    //      if (bcActivityId != null)
    //      {
    //         metaValues.add(buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, Integer.toString(bcActivityId)));
    //      }
    ContentResolver resolver = mContext.getContentResolver();
    resolver.bulkInsert(metadataUri, metaValues.toArray(new ContentValues[1]));

    tracks.addSyncedTrack(ogtTrackId, mTrack.second);

}

From source file:net.naonedbus.manager.impl.CommentaireManager.java

private void fillDB(final ContentResolver contentResolver, final List<Commentaire> commentaires) {
    final ContentValues[] values = new ContentValues[commentaires.size()];
    for (int i = 0; i < commentaires.size(); i++) {
        values[i] = getContentValues(commentaires.get(i));
    }/*  w  w w .j a va2s. co  m*/

    contentResolver.bulkInsert(CommentaireProvider.CONTENT_URI, values);
}

From source file:com.mutu.gpstracker.breadcrumbs.UploadBreadcrumbsTrackTask.java

@Override
protected void onPostExecute(Uri result) {
    BreadcrumbsTracks tracks = mService.getBreadcrumbsTracks();
    Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata");
    List<String> segments = result.getPathSegments();
    Integer bcTrackId = Integer.valueOf(segments.get(segments.size() - 2));

    ArrayList<ContentValues> metaValues = new ArrayList<ContentValues>();

    metaValues.add(buildContentValues(BreadcrumbsTracks.TRACK_ID, Long.toString(bcTrackId)));
    if (mDescription != null) {
        metaValues.add(buildContentValues(BreadcrumbsTracks.DESCRIPTION, mDescription));
    }//ww w  . j a  v  a2  s  .co m
    if (mIsPublic != null) {
        metaValues.add(buildContentValues(BreadcrumbsTracks.ISPUBLIC, mIsPublic));
    }
    metaValues.add(buildContentValues(BreadcrumbsTracks.BUNDLE_ID, mBundleId));
    metaValues.add(buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, mActivityId));

    // Store in OGT provider
    ContentResolver resolver = mContext.getContentResolver();
    resolver.bulkInsert(metadataUri, metaValues.toArray(new ContentValues[1]));

    // Store in Breadcrumbs adapter
    tracks.addSyncedTrack(Long.valueOf(mTrackUri.getLastPathSegment()), bcTrackId);
    if (mIsBundleCreated) {
        mService.getBreadcrumbsTracks().addBundle(Integer.parseInt(mBundleId), mBundleName, mBundleDescription);
    }
    //"http://api.gobreadcrumbs.com/v1/tracks/" + trackId + "/placemarks.gpx"
    mService.getBreadcrumbsTracks().addTrack(bcTrackId, mName, Integer.valueOf(mBundleId), mDescription, null,
            null, null, mIsPublic, null, null, null, null, null);

    super.onPostExecute(result);
}

From source file:com.jackie.sunshine.app.sync.SunshineSyncAdapter.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p>/* ww  w . jav a2s  . c  o  m*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        GregorianCalendar calendar = new GregorianCalendar();
        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);

            ContentResolver contentResolver = getContext().getContentResolver();
            inserted = contentResolver.bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
            contentResolver.delete(WeatherEntry.CONTENT_URI, WeatherEntry.COLUMN_DATE + "<= " + "?",
                    new String[] { Long.toString(dayTime.setJulianDay(julianStartDay - 1)) });

            notifyWeather();
        }
        Log.d(TAG, "getWeatherDataFromJson: " + inserted + " inserted");
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}