Search in sources :

Example 1 with ContentProviderOperation

use of android.content.ContentProviderOperation in project AndroidSyncProviderDemo by c99koder.

the class ContactsSyncAdapterService method updateContactStatus.

private static void updateContactStatus(ArrayList<ContentProviderOperation> operationList, long rawContactId, String status) {
    Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
    Uri entityUri = Uri.withAppendedPath(rawContactUri, Entity.CONTENT_DIRECTORY);
    Cursor c = mContentResolver.query(entityUri, new String[] { RawContacts.SOURCE_ID, Entity.DATA_ID, Entity.MIMETYPE, Entity.DATA1 }, null, null, null);
    try {
        while (c.moveToNext()) {
            if (!c.isNull(1)) {
                String mimeType = c.getString(2);
                if (mimeType.equals("vnd.android.cursor.item/vnd.org.c99.SyncProviderDemo.profile")) {
                    ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(ContactsContract.StatusUpdates.CONTENT_URI);
                    builder.withValue(ContactsContract.StatusUpdates.DATA_ID, c.getLong(1));
                    builder.withValue(ContactsContract.StatusUpdates.STATUS, status);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_RES_PACKAGE, "org.c99.SyncProviderDemo");
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_LABEL, R.string.app_name);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_ICON, R.drawable.icon);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_TIMESTAMP, System.currentTimeMillis());
                    operationList.add(builder.build());
                    //statuses elsewhere
                    if (Integer.decode(Build.VERSION.SDK) < 11) {
                        builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
                        builder.withSelection(BaseColumns._ID + " = '" + c.getLong(1) + "'", null);
                        builder.withValue(ContactsContract.Data.DATA3, status);
                        operationList.add(builder.build());
                    }
                }
            }
        }
    } finally {
        c.close();
    }
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) Cursor(android.database.Cursor) Uri(android.net.Uri)

Example 2 with ContentProviderOperation

use of android.content.ContentProviderOperation in project AndroidSyncProviderDemo by c99koder.

the class ContactsSyncAdapterService method performSync.

private static void performSync(Context context, Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) throws OperationCanceledException {
    HashMap<String, SyncEntry> localContacts = new HashMap<String, SyncEntry>();
    mContentResolver = context.getContentResolver();
    Log.i(TAG, "performSync: " + account.toString());
    // Load the local contacts
    Uri rawContactUri = RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name).appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type).build();
    Cursor c1 = mContentResolver.query(rawContactUri, new String[] { BaseColumns._ID, UsernameColumn, PhotoTimestampColumn }, null, null, null);
    while (c1.moveToNext()) {
        SyncEntry entry = new SyncEntry();
        entry.raw_id = c1.getLong(c1.getColumnIndex(BaseColumns._ID));
        entry.photo_timestamp = c1.getLong(c1.getColumnIndex(PhotoTimestampColumn));
        localContacts.put(c1.getString(1), entry);
    }
    ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
    try {
        // status message
        if (localContacts.get("efudd") == null) {
            addContact(account, "Elmer Fudd", "efudd");
        } else {
            if (localContacts.get("efudd").photo_timestamp == null || System.currentTimeMillis() > (localContacts.get("efudd").photo_timestamp + 604800000L)) {
                //You would probably download an image file and just pass the bytes, but this sample doesn't use network so we'll decode and re-compress the icon resource to get the bytes
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
                icon.compress(CompressFormat.PNG, 0, stream);
                updateContactPhoto(operationList, localContacts.get("efudd").raw_id, stream.toByteArray());
            }
            updateContactStatus(operationList, localContacts.get("efudd").raw_id, "hunting wabbits");
        }
        if (operationList.size() > 0)
            mContentResolver.applyBatch(ContactsContract.AUTHORITY, operationList);
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) Bitmap(android.graphics.Bitmap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Cursor(android.database.Cursor) Uri(android.net.Uri) OperationCanceledException(android.accounts.OperationCanceledException)

Example 3 with ContentProviderOperation

use of android.content.ContentProviderOperation in project SeriesGuide by UweTrottmann.

the class TvdbTools method addShow.

/**
     * Adds a show and its episodes to the database. If the show already exists, does nothing.
     *
     * <p> If signed in to Hexagon, gets show properties and episode flags.
     *
     * <p> If connected to trakt, but not signed in to Hexagon, gets episode flags from trakt
     * instead.
     *
     * @return True, if the show and its episodes were added to the database.
     */
public boolean addShow(int showTvdbId, @Nullable String language, @Nullable HashMap<Integer, BaseShow> traktCollection, @Nullable HashMap<Integer, BaseShow> traktWatched) throws TvdbException {
    boolean isShowExists = DBUtils.isShowExists(app, showTvdbId);
    if (isShowExists) {
        return false;
    }
    // get show and determine the language to use
    Show show = getShowDetailsWithHexagon(showTvdbId, language);
    language = show.language;
    // get episodes and store everything to the database
    final ArrayList<ContentProviderOperation> batch = new ArrayList<>();
    batch.add(DBUtils.buildShowOp(app, show, true));
    getEpisodesAndUpdateDatabase(batch, show, language);
    // restore episode flags...
    if (HexagonSettings.isEnabled(app)) {
        // ...from Hexagon
        boolean success = EpisodeTools.Download.flagsFromHexagon(app, showTvdbId);
        if (!success) {
            // failed to download episode flags
            // flag show as needing an episode merge
            ContentValues values = new ContentValues();
            values.put(Shows.HEXAGON_MERGE_COMPLETE, false);
            app.getContentResolver().update(Shows.buildShowUri(showTvdbId), values, null, null);
        }
        // flag show to be auto-added (again), send (new) language to Hexagon
        app.getShowTools().sendIsAdded(showTvdbId, language);
    } else {
        // ...from trakt
        TraktTools traktTools = app.getTraktTools();
        if (!traktTools.storeEpisodeFlags(traktWatched, showTvdbId, TraktTools.Flag.WATCHED)) {
            throw new TvdbDataException("addShow: storing trakt watched episodes failed.");
        }
        if (!traktTools.storeEpisodeFlags(traktCollection, showTvdbId, TraktTools.Flag.COLLECTED)) {
            throw new TvdbDataException("addShow: storing trakt collected episodes failed.");
        }
    }
    // calculate next episode
    DBUtils.updateLatestEpisode(app, showTvdbId);
    return true;
}
Also used : ContentValues(android.content.ContentValues) ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) BaseShow(com.uwetrottmann.trakt5.entities.BaseShow) Show(com.battlelancer.seriesguide.dataliberation.model.Show) TraktTools(com.battlelancer.seriesguide.util.TraktTools)

Example 4 with ContentProviderOperation

use of android.content.ContentProviderOperation in project SeriesGuide by UweTrottmann.

the class TvdbTools method updateShow.

/**
     * Updates a show. Adds new, updates changed and removes orphaned episodes.
     */
public void updateShow(int showTvdbId) throws TvdbException {
    // determine which translation to get
    String language = getShowLanguage(app, showTvdbId);
    if (language == null) {
        return;
    }
    final ArrayList<ContentProviderOperation> batch = new ArrayList<>();
    Show show = getShowDetails(showTvdbId, language);
    batch.add(DBUtils.buildShowOp(app, show, false));
    // get episodes in the language as returned in the TVDB show entry
    // the show might not be available in the desired language
    getEpisodesAndUpdateDatabase(batch, show, show.language);
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) BaseShow(com.uwetrottmann.trakt5.entities.BaseShow) Show(com.battlelancer.seriesguide.dataliberation.model.Show)

Example 5 with ContentProviderOperation

use of android.content.ContentProviderOperation in project SeriesGuide by UweTrottmann.

the class DBUtils method updateLatestEpisode.

/**
     * Update next episode field and unwatched episode count for the given show. If no show id is
     * passed, will update next episodes for all shows.
     *
     * @return If only one show was passed, the TVDb id of the new next episode. Otherwise -1.
     */
public static long updateLatestEpisode(Context context, Integer showTvdbIdToUpdate) {
    // get a list of shows and their last watched episodes
    Cursor shows;
    try {
        shows = context.getContentResolver().query(Shows.CONTENT_URI_WITH_LAST_EPISODE, LastWatchedEpisodeQuery.PROJECTION, showTvdbIdToUpdate != null ? Qualified.SHOWS_ID + "=" + showTvdbIdToUpdate : null, null, null);
    } catch (SQLiteException e) {
        shows = null;
        Timber.e(e, "updateLatestEpisode: show query failed.");
        postDatabaseError(e);
    }
    if (shows == null) {
        // abort completely on query failure
        Timber.e("Failed to update next episode values");
        return -1;
    }
    final List<String[]> showsLastEpisodes = new ArrayList<>();
    while (shows.moveToNext()) {
        showsLastEpisodes.add(new String[] { // 0
        shows.getString(LastWatchedEpisodeQuery.SHOW_TVDB_ID), // 1
        shows.getString(LastWatchedEpisodeQuery.LAST_EPISODE_TVDB_ID), // 2
        shows.getString(LastWatchedEpisodeQuery.LAST_EPISODE_SEASON), // 3
        shows.getString(LastWatchedEpisodeQuery.LAST_EPISODE_NUMBER), shows.getString(LastWatchedEpisodeQuery.LAST_EPISODE_FIRST_RELEASE_MS) });
    }
    shows.close();
    // pre-build next episode selection
    final boolean isNoReleasedEpisodes = DisplaySettings.isNoReleasedEpisodes(context);
    final String nextEpisodeSelection = buildNextEpisodeSelection(DisplaySettings.isHidingSpecials(context), isNoReleasedEpisodes);
    // build updated next episode values for each show
    int nextEpisodeTvdbId = -1;
    final ContentValues newShowValues = new ContentValues();
    final ArrayList<ContentProviderOperation> batch = new ArrayList<>();
    final String currentTime = String.valueOf(TimeTools.getCurrentTime(context));
    final boolean displayExactDate = DisplaySettings.isDisplayExactDate(context);
    DisplaySettings.preventSpoilers(context);
    for (String[] show : showsLastEpisodes) {
        // STEP 1: get last watched episode details
        final String showTvdbId = show[0];
        final String lastEpisodeTvdbId = show[1];
        String season = show[2];
        String number = show[3];
        String releaseTime = show[4];
        if (TextUtils.isEmpty(lastEpisodeTvdbId) || season == null || number == null || releaseTime == null) {
            // by default: no watched episodes, include all starting with special 0
            season = "-1";
            number = "-1";
            releaseTime = String.valueOf(Long.MIN_VALUE);
        }
        // STEP 2: get episode released closest afterwards; or at the same time,
        // but with a higher number
        final String[] selectionArgs;
        if (isNoReleasedEpisodes) {
            // restrict to episodes with future release date
            selectionArgs = new String[] { releaseTime, number, season, releaseTime, currentTime };
        } else {
            // restrict to episodes with any valid air date
            selectionArgs = new String[] { releaseTime, number, season, releaseTime };
        }
        Cursor next;
        try {
            next = context.getContentResolver().query(Episodes.buildEpisodesOfShowUri(showTvdbId), NextEpisodesQuery.PROJECTION, nextEpisodeSelection, selectionArgs, NextEpisodesQuery.SORTORDER);
        } catch (SQLiteException e) {
            next = null;
            Timber.e(e, "updateLatestEpisode: next episode query failed.");
            postDatabaseError(e);
        }
        if (next == null) {
            // abort completely on query failure
            Timber.e("Failed to update next episode values");
            return -1;
        }
        // STEP 3: build updated next episode values
        if (next.moveToFirst()) {
            final String nextEpisodeString;
            int seasonNumber = next.getInt(NextEpisodesQuery.SEASON);
            int episodeNumber = next.getInt(NextEpisodesQuery.NUMBER);
            if (DisplaySettings.preventSpoilers(context)) {
                // just the number, like '0x12'
                nextEpisodeString = TextTools.getEpisodeNumber(context, seasonNumber, episodeNumber);
            } else {
                // next episode text, like '0x12 Episode Name'
                nextEpisodeString = TextTools.getNextEpisodeString(context, seasonNumber, episodeNumber, next.getString(NextEpisodesQuery.TITLE));
            }
            // next release date text, e.g. "in 15 mins (Fri)"
            long releaseTimeNext = next.getLong(NextEpisodesQuery.FIRST_RELEASE_MS);
            Date actualRelease = TimeTools.applyUserOffset(context, releaseTimeNext);
            String dateTime = displayExactDate ? TimeTools.formatToLocalDateShort(context, actualRelease) : TimeTools.formatToLocalRelativeTime(context, actualRelease);
            final String nextReleaseDateString = context.getString(R.string.release_date_and_day, dateTime, TimeTools.formatToLocalDay(actualRelease));
            nextEpisodeTvdbId = next.getInt(NextEpisodesQuery.ID);
            newShowValues.put(Shows.NEXTEPISODE, nextEpisodeTvdbId);
            newShowValues.put(Shows.NEXTAIRDATEMS, releaseTimeNext);
            newShowValues.put(Shows.NEXTTEXT, nextEpisodeString);
            newShowValues.put(Shows.NEXTAIRDATETEXT, nextReleaseDateString);
        } else {
            // no next episode, set empty values
            nextEpisodeTvdbId = 0;
            newShowValues.put(Shows.NEXTEPISODE, "");
            newShowValues.put(Shows.NEXTAIRDATEMS, UNKNOWN_NEXT_RELEASE_DATE);
            newShowValues.put(Shows.NEXTTEXT, "");
            newShowValues.put(Shows.NEXTAIRDATETEXT, "");
        }
        next.close();
        // STEP 4: get remaining episodes count
        int unwatchedEpisodesCount = getUnwatchedEpisodesOfShow(context, showTvdbId);
        newShowValues.put(Shows.UNWATCHED_COUNT, unwatchedEpisodesCount);
        // update the show with the new next episode values
        batch.add(ContentProviderOperation.newUpdate(Shows.buildShowUri(showTvdbId)).withValues(newShowValues).build());
        newShowValues.clear();
    }
    try {
        DBUtils.applyInSmallBatches(context, batch);
    } catch (OperationApplicationException e) {
        Timber.e(e, "Failed to update next episode values");
        return -1;
    }
    return nextEpisodeTvdbId;
}
Also used : ContentValues(android.content.ContentValues) ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) SQLiteException(android.database.sqlite.SQLiteException) Date(java.util.Date) OperationApplicationException(android.content.OperationApplicationException)

Aggregations

ContentProviderOperation (android.content.ContentProviderOperation)75 ArrayList (java.util.ArrayList)53 OperationApplicationException (android.content.OperationApplicationException)34 Uri (android.net.Uri)27 ContentValues (android.content.ContentValues)25 RemoteException (android.os.RemoteException)22 Cursor (android.database.Cursor)14 ContentProviderResult (android.content.ContentProviderResult)13 ContentResolver (android.content.ContentResolver)9 LinkedList (java.util.LinkedList)8 IOException (java.io.IOException)7 JSONArray (org.json.JSONArray)6 JSONException (org.json.JSONException)6 JSONObject (org.json.JSONObject)6 Intent (android.content.Intent)5 List (java.util.List)5 SuppressLint (android.annotation.SuppressLint)4 BroadcastReceiver (android.content.BroadcastReceiver)4 Context (android.content.Context)4 IntentFilter (android.content.IntentFilter)4