Java Code Examples for android.content.ContentResolver#bulkInsert()

The following examples show how to use android.content.ContentResolver#bulkInsert() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MusicUtils.java    From Rey-MusicPlayer with Apache License 2.0 6 votes vote down vote up
public static void addToPlaylist(Context context, long[] ids, long playlistid) {
    if (ids == null) {
        Log.e("MusicBase", "ListSelection null");
    } else {
        int size = ids.length;
        ContentResolver resolver = context.getContentResolver();
        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);
        }
    }
}
 
Example 2
Source File: SyncTVShows.java    From Kore with Apache License 2.0 6 votes vote down vote up
public void insertSeason(int tvshowId, List<VideoType.DetailsSeason> result, ContentResolver contentResolver) {
    ContentValues[] seasonsValuesBatch = new ContentValues[result.size()];
    int totalWatchedEpisodes = 0;
    for (int i = 0; i < result.size(); i++) {
        VideoType.DetailsSeason season = result.get(i);
        seasonsValuesBatch[i] = SyncUtils.contentValuesFromSeason(hostId, season);

        totalWatchedEpisodes += season.watchedepisodes;
    }
    // Insert the seasons
    contentResolver.bulkInsert(MediaContract.Seasons.CONTENT_URI, seasonsValuesBatch);

    if (getSyncType().equals(LibrarySyncService.SYNC_SINGLE_TVSHOW)) {
        // HACK: Update watched episodes count for the tvshow with the sum
        // of watched episodes from seasons, given that the value that we
        // got from XBMC from the call to GetTVShowDetails is wrong (note
        // that the value returned from GetTVShows is correct).
        Uri uri = MediaContract.TVShows.buildTVShowUri(hostId, tvshowId);
        ContentValues tvshowUpdate = new ContentValues(1);
        tvshowUpdate.put(MediaContract.TVShowsColumns.WATCHEDEPISODES, totalWatchedEpisodes);
        contentResolver.update(uri, tvshowUpdate, null, null);
    }
}
 
Example 3
Source File: RemotePreferenceProviderTest.java    From RemotePreferences with MIT License 6 votes vote down vote up
@Test
public void testInsertMultiplePrefs() {
    ContentValues[] values = new ContentValues[2];
    values[0] = new ContentValues();
    values[0].put(RemoteContract.COLUMN_KEY, "string");
    values[0].put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING);
    values[0].put(RemoteContract.COLUMN_VALUE, "foobar");

    values[1] = new ContentValues();
    values[1].put(RemoteContract.COLUMN_KEY, "int");
    values[1].put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_INT);
    values[1].put(RemoteContract.COLUMN_VALUE, 1337);

    ContentResolver resolver = getLocalContext().getContentResolver();
    int ret = resolver.bulkInsert(getQueryUri(null), values);
    Assert.assertEquals(2, ret);

    SharedPreferences prefs = getSharedPreferences();
    Assert.assertEquals("foobar", prefs.getString("string", null));
    Assert.assertEquals(1337, prefs.getInt("int", 0));
}
 
Example 4
Source File: RemotePreferenceProviderTest.java    From RemotePreferences with MIT License 6 votes vote down vote up
@Test
public void testInsertFailPermissionCheck() {
    ContentValues[] values = new ContentValues[2];
    values[0] = new ContentValues();
    values[0].put(RemoteContract.COLUMN_KEY, "string");
    values[0].put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING);
    values[0].put(RemoteContract.COLUMN_VALUE, "foobar");

    values[1] = new ContentValues();
    values[1].put(RemoteContract.COLUMN_KEY, Constants.UNWRITABLE_PREF_KEY);
    values[1].put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_INT);
    values[1].put(RemoteContract.COLUMN_VALUE, 1337);

    ContentResolver resolver = getLocalContext().getContentResolver();
    try {
        resolver.bulkInsert(getQueryUri(null), values);
        Assert.fail();
    } catch (SecurityException e) {
        // Expected
    }

    SharedPreferences prefs = getSharedPreferences();
    Assert.assertEquals("default", prefs.getString("string", "default"));
    Assert.assertEquals(0, prefs.getInt(Constants.UNWRITABLE_PREF_KEY, 0));
}
 
Example 5
Source File: ImConnectionAdapter.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
void saveSessionCookie(ContentResolver cr) {
    Map<String, String> cookies = mConnection.getSessionContext();

    int i = 0;
    ContentValues[] valuesList = new ContentValues[cookies.size()];

    for (Map.Entry<String, String> entry : cookies.entrySet()) {
        ContentValues values = new ContentValues(2);

        values.put(Imps.SessionCookies.NAME, entry.getKey());
        values.put(Imps.SessionCookies.VALUE, entry.getValue());

        valuesList[i++] = values;
    }

    cr.bulkInsert(getSessionCookiesUri(), valuesList);
}
 
Example 6
Source File: SyncMusic.java    From Kore with Apache License 2.0 5 votes vote down vote up
public void insertGenresItems(int hostId, List<LibraryType.DetailsGenre> items, ContentResolver contentResolver) {
    ContentValues genresValuesBatch[] = new ContentValues[items.size()];

    for (int i = 0; i < items.size(); i++) {
        LibraryType.DetailsGenre genre = items.get(i);
        genresValuesBatch[i] = SyncUtils.contentValuesFromAudioGenre(hostId, genre);
    }

    // Insert the genres and proceed to albums
    contentResolver.bulkInsert(MediaContract.AudioGenres.CONTENT_URI, genresValuesBatch);
}
 
Example 7
Source File: MusicPlayer.java    From Muzesto with GNU General Public License v3.0 5 votes vote down vote up
public static void addToPlaylist(final Context context, final long[] ids, final long playlistid) {
    final int size = ids.length;
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + "play_order" + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
    Cursor cursor = null;
    int base = 0;

    try {
        cursor = resolver.query(uri, projection, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            base = cursor.getInt(0) + 1;
        }
    } finally {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }

    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);
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
 
Example 8
Source File: PlaylistsUtil.java    From VinylMusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
public static void addToPlaylist(@NonNull final Context context, @NonNull final List<Song> songs, final int playlistId, final boolean showToastOnFinish) {
    final int size = songs.size();
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + MediaStore.Audio.Playlists.Members.PLAY_ORDER + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    Cursor cursor = null;
    int base = 0;

    try {
        try {
            cursor = resolver.query(uri, projection, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                base = cursor.getInt(0) + 1;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        int numInserted = 0;
        for (int offSet = 0; offSet < size; offSet += 1000)
            numInserted += resolver.bulkInsert(uri, makeInsertItems(songs, offSet, 1000, base));

        if (showToastOnFinish) {
            Toast.makeText(context, context.getResources().getString(
                    R.string.inserted_x_songs_into_playlist_x, numInserted, getNameForPlaylist(context, playlistId)), Toast.LENGTH_SHORT).show();
        }
    } catch (SecurityException ignored) {
    }
}
 
Example 9
Source File: PlaylistsUtil.java    From RetroMusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
public static void addToPlaylist(@NonNull final Context context, @NonNull final List<Song> songs, final int playlistId, final boolean showToastOnFinish) {
    final int size = songs.size();
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + MediaStore.Audio.Playlists.Members.PLAY_ORDER + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    Cursor cursor = null;
    int base = 0;

    try {
        try {
            cursor = resolver.query(uri, projection, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                base = cursor.getInt(0) + 1;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        int numInserted = 0;
        for (int offSet = 0; offSet < size; offSet += 1000)
            numInserted += resolver.bulkInsert(uri, makeInsertItems(songs, offSet, 1000, base));

        if (showToastOnFinish) {
            Toast.makeText(context, context.getResources().getString(
                    R.string.inserted_x_songs_into_playlist_x, numInserted, getNameForPlaylist(context, playlistId)), Toast.LENGTH_SHORT).show();
        }
    } catch (SecurityException ignored) {
    }
}
 
Example 10
Source File: PlaylistsUtil.java    From Phonograph with GNU General Public License v3.0 5 votes vote down vote up
public static void addToPlaylist(@NonNull final Context context, @NonNull final List<Song> songs, final int playlistId, final boolean showToastOnFinish) {
    final int size = songs.size();
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + MediaStore.Audio.Playlists.Members.PLAY_ORDER + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    Cursor cursor = null;
    int base = 0;

    try {
        try {
            cursor = resolver.query(uri, projection, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                base = cursor.getInt(0) + 1;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        int numInserted = 0;
        for (int offSet = 0; offSet < size; offSet += 1000)
            numInserted += resolver.bulkInsert(uri, makeInsertItems(songs, offSet, 1000, base));

        if (showToastOnFinish) {
            Toast.makeText(context, context.getResources().getString(
                    R.string.inserted_x_songs_into_playlist_x, numInserted, getNameForPlaylist(context, playlistId)), Toast.LENGTH_SHORT).show();
        }
    } catch (SecurityException ignored) {
    }
}
 
Example 11
Source File: ImPluginHelper.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
private long insertProviderDb(ImPlugin plugin, ImPluginInfo info, String providerFullName,
        String signUpUrl) {
    Map<String, String> config = loadConfiguration(plugin, info);
    if (config == null) {
        return 0;
    }

    long providerId = 0;
    ContentResolver cr = mContext.getContentResolver();
    ContentValues values = new ContentValues(3);
    values.put(Imps.Provider.NAME, info.mProviderName);
    values.put(Imps.Provider.FULLNAME, providerFullName);
    values.put(Imps.Provider.CATEGORY, ImApp.IMPS_CATEGORY);
    values.put(Imps.Provider.SIGNUP_URL, signUpUrl);

    Uri result = cr.insert(Imps.Provider.CONTENT_URI, values);
    if (result == null)
        return -1;

    providerId = ContentUris.parseId(result);

    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;
    }
    cr.bulkInsert(Imps.ProviderSettings.CONTENT_URI, settingValues);

    return providerId;
}
 
Example 12
Source File: PlaylistsUtil.java    From MusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
public static void addToPlaylist(@NonNull final Context context, @NonNull final List<Song> songs, final int playlistId, final boolean showToastOnFinish) {
    final int size = songs.size();
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + MediaStore.Audio.Playlists.Members.PLAY_ORDER + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    Cursor cursor = null;
    int base = 0;

    try {
        try {
            cursor = resolver.query(uri, projection, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                base = cursor.getInt(0) + 1;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        int numInserted = 0;
        for (int offSet = 0; offSet < size; offSet += 1000)
            numInserted += resolver.bulkInsert(uri, makeInsertItems(songs, offSet, 1000, base));

        if (showToastOnFinish) {
            Toast.makeText(context, context.getResources().getString(
                    R.string.inserted_x_songs_into_playlist_x, numInserted, getNameForPlaylist(context, playlistId)), Toast.LENGTH_SHORT).show();
        }
    } catch (SecurityException ignored) {
    }
}
 
Example 13
Source File: QuantumFlux.java    From QuantumFlux with Apache License 2.0 5 votes vote down vote up
public static <T> int insertAll(List<T> dataModelObjects) {
    if (dataModelObjects == null || dataModelObjects.isEmpty())
        return 0;

    TableDetails tableDetails = findTableDetails(dataModelObjects.get(0).getClass());
    Uri insertUri = UriMatcherHelper.generateItemUriBuilder(tableDetails).build();

    ContentValues[] values = new ContentValues[dataModelObjects.size()];
    for (int i = 0; i < dataModelObjects.size(); i++) {
        values[i] = ModelInflater.deflate(tableDetails, dataModelObjects.get(i));
    }

    ContentResolver contentResolver = mApplicationContext.getContentResolver();
    return contentResolver.bulkInsert(insertUri, values);
}
 
Example 14
Source File: PlaylistsUtil.java    From Music-Player with GNU General Public License v3.0 5 votes vote down vote up
public static void addToPlaylist(@NonNull final Context context, @NonNull final List<Song> songs, final int playlistId, final boolean showToastOnFinish) {
    final int size = songs.size();
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + MediaStore.Audio.Playlists.Members.PLAY_ORDER + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    Cursor cursor = null;
    int base = 0;

    try {
        try {
            cursor = resolver.query(uri, projection, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                base = cursor.getInt(0) + 1;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        int numInserted = 0;
        for (int offSet = 0; offSet < size; offSet += 1000)
            numInserted += resolver.bulkInsert(uri, makeInsertItems(songs, offSet, 1000, base));

        if (showToastOnFinish) {
    		Toast.makeText(context, context.getResources().getQuantityString(
            		R.plurals.inserted_x_songs_into_playlist_x, numInserted, numInserted, getNameForPlaylist(context, playlistId)), Toast.LENGTH_SHORT).show();
        }
    } catch (SecurityException ignored) {
    }
}
 
Example 15
Source File: SunshineSyncTask.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * 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
 */
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();
    }
}
 
Example 16
Source File: SunshineSyncTask.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * 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
 */
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);
        }

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

    } catch (Exception e) {
        /* Server probably invalid */
        e.printStackTrace();
    }
}
 
Example 17
Source File: SunshineSyncTask.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
     * 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
     */
    synchronized public static void syncWeather(Context context) {

//      COMPLETED (3) Within syncWeather, fetch new weather data

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

//              COMPLETED (4) If we have valid results, delete the old data and insert the new
                /* 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);
            }

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

        } catch (Exception e) {
            /* Server probably invalid */
            e.printStackTrace();
        }
    }
 
Example 18
Source File: CalendarIntegrationService.java    From prayer-times-android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onHandleIntent(@NonNull Intent intent) {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        Preferences.CALENDAR_INTEGRATION.set("-1");
        return;
    }
    Context context = App.get();
    try {
        ContentResolver cr = context.getContentResolver();


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

        Uri calenderUri = CalendarContract.Calendars.CONTENT_URI.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT_NAME)
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE).build();
        cr.delete(calenderUri,
                CalendarContract.Calendars.ACCOUNT_NAME + " = ? AND " + CalendarContract.Calendars.ACCOUNT_TYPE + " = ?",
                new String[]{ACCOUNT_NAME, ACCOUNT_TYPE});

        String id = Preferences.CALENDAR_INTEGRATION.get();

        if ("-1".equals(id)) {
            return;
        }

        List<ContentValues> events = new ArrayList<>();
        long calendarId = getCalendar(context);
        for (int year = HijriDate.getMinGregYear(); year <= HijriDate.getMaxGregYear(); year++) {


            for (Pair<HijriDate, Integer> date : HijriDate.getHolydaysForGregYear(year)) {
                if (date == null || date.second <= 0)
                    continue;
                ContentValues event = new ContentValues();

                event.put(CalendarContract.Events.CALENDAR_ID, calendarId);
                event.put(CalendarContract.Events.TITLE, LocaleUtils.getHolyday(date.second));
                event.put(CalendarContract.Events.DESCRIPTION, "com.metinkale.prayer");
                LocalDate ld = date.first.getLocalDate();
                DateTime cal = ld.toDateTimeAtStartOfDay(DateTimeZone.UTC);

                long dtstart = cal.getMillis();
                long dtend = cal.plusDays(1).getMillis();

                event.put(CalendarContract.Events.DTSTART, dtstart);
                event.put(CalendarContract.Events.DTEND, 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);
                event.put(CalendarContract.Events.HAS_ALARM, 0);
                event.put(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_FREE);
                event.put(CalendarContract.Events.CUSTOM_APP_PACKAGE, getPackageName());
                event.put(CalendarContract.Events.CUSTOM_APP_URI, "https://prayerapp.page.link/calendar");


                events.add(event);
            }
        }
        cr.bulkInsert(CalendarContract.Events.CONTENT_URI, events.toArray(new ContentValues[0]));
    } catch (Exception e) {
        Preferences.CALENDAR_INTEGRATION.set("-1");
        Crashlytics.logException(e);
    }

}
 
Example 19
Source File: SunshineSyncTask.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * 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
 */
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();
    }
}
 
Example 20
Source File: CalendarIntegrationService.java    From prayer-times-android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onHandleIntent(@NonNull Intent intent) {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        Preferences.CALENDAR_INTEGRATION.set("-1");
        return;
    }
    Context context = App.get();
    try {
        ContentResolver cr = context.getContentResolver();


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

        Uri calenderUri = CalendarContract.Calendars.CONTENT_URI.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT_NAME)
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE).build();
        cr.delete(calenderUri,
                CalendarContract.Calendars.ACCOUNT_NAME + " = ? AND " + CalendarContract.Calendars.ACCOUNT_TYPE + " = ?",
                new String[]{ACCOUNT_NAME, ACCOUNT_TYPE});

        String id = Preferences.CALENDAR_INTEGRATION.get();

        if ("-1".equals(id)) {
            return;
        }

        List<ContentValues> events = new ArrayList<>();
        long calendarId = getCalendar(context);
        for (int year = HijriDate.getMinGregYear(); year <= HijriDate.getMaxGregYear(); year++) {


            for (Pair<HijriDate, Integer> date : HijriDate.getHolydaysForGregYear(year)) {
                if (date == null || date.second <= 0)
                    continue;
                ContentValues event = new ContentValues();

                event.put(CalendarContract.Events.CALENDAR_ID, calendarId);
                event.put(CalendarContract.Events.TITLE, LocaleUtils.getHolyday(date.second));
                event.put(CalendarContract.Events.DESCRIPTION, "com.metinkale.prayer");
                LocalDate ld = date.first.getLocalDate();
                DateTime cal = ld.toDateTimeAtStartOfDay(DateTimeZone.UTC);

                long dtstart = cal.getMillis();
                long dtend = cal.plusDays(1).getMillis();

                event.put(CalendarContract.Events.DTSTART, dtstart);
                event.put(CalendarContract.Events.DTEND, 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);
                event.put(CalendarContract.Events.HAS_ALARM, 0);
                event.put(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_FREE);
                event.put(CalendarContract.Events.CUSTOM_APP_PACKAGE, getPackageName());
                event.put(CalendarContract.Events.CUSTOM_APP_URI, "https://prayerapp.page.link/calendar");


                events.add(event);
            }
        }
        cr.bulkInsert(CalendarContract.Events.CONTENT_URI, events.toArray(new ContentValues[0]));
    } catch (Exception e) {
        Preferences.CALENDAR_INTEGRATION.set("-1");
        Crashlytics.logException(e);
    }

}