Example usage for android.content ContentUris withAppendedId

List of usage examples for android.content ContentUris withAppendedId

Introduction

In this page you can find the example usage for android.content ContentUris withAppendedId.

Prototype

public static Uri withAppendedId(Uri contentUri, long id) 

Source Link

Document

Appends the given ID to the end of the path.

Usage

From source file:com.example.android.pharmacyinventory.EditorActivity.java

@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor cursor) {
    // Bail early if the cursor is null or there is less than 1 row in the cursor
    if (cursor == null || cursor.getCount() < 1) {
        return;/*from  w  w  w . j a  v  a  2  s . c  o m*/
    }

    // Proceed with moving to the first row of the cursor and reading data from it
    // (This should be the only row in the cursor)
    if (cursor.moveToFirst()) {
        // Find the columns of drug attributes that we're interested in
        int nameColumnIndex = cursor.getColumnIndex(DrugContract.DrugEntry.COLUMN_DRUG_NAME);
        int quantityColumnIndex = cursor.getColumnIndex(DrugContract.DrugEntry.COLUMN_DRUG_QUANTITY);
        int priceColumnIndex = cursor.getColumnIndex(DrugContract.DrugEntry.COLUMN_DRUG_PRICE);
        int imageColumnIndex = cursor.getColumnIndex(DrugContract.DrugEntry.COLUMN_DRUG_IMAGE);

        // Extract out the value from the Cursor for the given column index
        String name = cursor.getString(nameColumnIndex);
        int quantity = cursor.getInt(quantityColumnIndex);
        Double price = cursor.getDouble(priceColumnIndex);
        String picture = cursor.getString(imageColumnIndex);

        // Update the views on the screen with the values from the database
        mNameEditText.setText(name);
        mQuantityText.setText(Integer.toString(quantity));
        mPriceEditText.setText(Double.toString(price));
        mDrugImage.setImageURI(Uri.parse(picture));
    }

    orderButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Get the Uri for the current drug
            int IdColumnIndex = cursor.getColumnIndex(DrugContract.DrugEntry._ID);
            final long itemId = cursor.getLong(IdColumnIndex);
            Uri mCurrentDrugUri = ContentUris.withAppendedId(DrugContract.DrugEntry.CONTENT_URI, itemId);

            // Find the columns of drug attributes that we're interested in
            int nameColumnIndex = cursor.getColumnIndex(DrugContract.DrugEntry.COLUMN_DRUG_NAME);

            // Read the Drug attributes from the Cursor for the current drug
            String name = cursor.getString(nameColumnIndex);

            // Read the drug name to use in subject line
            String subjectLine = "Need to order: " + name;

            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse("mailto:")); // only email apps should handle this
            intent.putExtra(Intent.EXTRA_EMAIL, "orders@gmail.com");
            intent.putExtra(Intent.EXTRA_SUBJECT, subjectLine);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            }
        }
    });

}

From source file:com.abcvoipsip.ui.account.AccountsEditListFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {

        if (requestCode == CHOOSE_WIZARD) {
            // Wizard has been choosen, now create an account
            String wizardId = data.getStringExtra(WizardUtils.ID);
            if (wizardId != null) {
                showDetails(SipProfile.INVALID_ID, wizardId);
            }//  w  w w . j a v  a 2s.  co m
        } else if (requestCode == CHANGE_WIZARD) {
            // Change wizard done for this account.
            String wizardId = data.getStringExtra(WizardUtils.ID);
            long accountId = data.getLongExtra(Intent.EXTRA_UID, SipProfile.INVALID_ID);

            if (wizardId != null && accountId != SipProfile.INVALID_ID) {
                ContentValues cv = new ContentValues();
                cv.put(SipProfile.FIELD_WIZARD, wizardId);
                getActivity().getContentResolver().update(
                        ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, accountId), cv, null, null);

            }

        }
    }

}

From source file:io.n7.calendar.caldav.CalDAVService.java

private void doSyncCalendar(Account acc, long calid) throws Exception {
    // Get a list of local events
    String[] evproj1 = new String[] { Events._ID, Events._SYNC_ID, Events.DELETED, Events._SYNC_DIRTY };
    HashMap<String, Long> localevs = new HashMap<String, Long>();
    HashMap<String, Long> removedevs = new HashMap<String, Long>();
    HashMap<String, Long> dirtyevs = new HashMap<String, Long>();
    HashMap<String, Long> newdevevs = new HashMap<String, Long>();

    Cursor c = mCR.query(EVENTS_URI, evproj1, Events.CALENDAR_ID + "=" + calid, null, null);

    long tid;// w w w  .  j a  v a 2 s.c o  m
    String tuid = null;
    if (c.moveToFirst()) {
        do {
            tid = c.getLong(0);
            tuid = c.getString(1);

            if (c.getInt(2) != 0)
                removedevs.put(tuid, tid);
            else if (tuid == null) {
                // generate a UUID
                tuid = UUID.randomUUID().toString();
                newdevevs.put(tuid, tid);
            } else if (c.getInt(3) != 0)
                dirtyevs.put(tuid, tid);
            else
                localevs.put(tuid, tid);
        } while (c.moveToNext());
        c.close();
    }

    CalDAV4jIf caldavif = new CalDAV4jIf(getAssets());
    caldavif.setCredentials(new CaldavCredential(acc.getProtocol(), acc.getHost(), acc.getPort(), acc.getHome(),
            acc.getCollection(), acc.getUser(), acc.getPassword()));

    //add new device events to server
    for (String uid : newdevevs.keySet())
        addEventOnServer(uid, newdevevs.get(uid), caldavif);
    //delete the locally removed events on server
    for (String uid : removedevs.keySet()) {
        removeEventOnServer(uid, caldavif);
        // clean up provider DB?
        removeLocalEvent(removedevs.get(uid));
    }

    //update the dirty events on server
    for (String uid : dirtyevs.keySet())
        updateEventOnServer(uid, dirtyevs.get(uid), caldavif);

    // Get events from server
    VEvent[] evs = caldavif.getEvents();

    // add/update to provider DB
    String[] evproj = new String[] { Events._ID };
    ContentValues cv = new ContentValues();
    String temp, durstr = null;
    for (VEvent v : evs) {
        cv.clear();
        durstr = null;

        String uid = ICalendarUtils.getUIDValue(v);
        // XXX Some times the server seem to return the deleted event if we do get events immediately
        // after removing..
        // So ignore the possibility of deleted event on server was modified on server, for now.
        if (removedevs.containsKey(uid))
            continue;

        //TODO: put etag here
        cv.put(Events._SYNC_ID, uid);
        //UUID
        cv.put(Events._SYNC_DATA, uid);

        cv.put(Events.CALENDAR_ID, calid);
        cv.put(Events.TITLE, ICalendarUtils.getSummaryValue(v));
        cv.put(Events.DESCRIPTION, ICalendarUtils.getPropertyValue(v, Property.DESCRIPTION));
        cv.put(Events.EVENT_LOCATION, ICalendarUtils.getPropertyValue(v, Property.LOCATION));
        String tzid = ICalendarUtils.getPropertyValue(v, Property.TZID);
        if (tzid == null)
            tzid = Time.getCurrentTimezone();
        cv.put(Events.EVENT_TIMEZONE, tzid);
        long dtstart = parseDateTimeToMillis(ICalendarUtils.getPropertyValue(v, Property.DTSTART), tzid);
        cv.put(Events.DTSTART, dtstart);

        temp = ICalendarUtils.getPropertyValue(v, Property.DTEND);
        if (temp != null)
            cv.put(Events.DTEND, parseDateTimeToMillis(temp, tzid));
        else {
            temp = ICalendarUtils.getPropertyValue(v, Property.DURATION);
            durstr = temp;
            if (temp != null) {
                cv.put(Events.DURATION, durstr);

                // We still need to calculate and enter DTEND. Otherwise, the Android is not displaying
                // the event properly
                Duration dur = new Duration();
                dur.parse(temp);
                cv.put(Events.DTEND, dtstart + dur.getMillis());
            }
        }

        //TODO add more fields

        //if the event is already present, update it otherwise insert it
        // TODO find if something changed on server using etag
        Uri euri;
        if (localevs.containsKey(uid) || dirtyevs.containsKey(uid)) {
            if (localevs.containsKey(uid)) {
                tid = localevs.get(uid);
                localevs.remove(uid);
            } else {
                tid = dirtyevs.get(uid);
                dirtyevs.remove(uid);
            }

            mCR.update(ContentUris.withAppendedId(EVENTS_URI, tid), cv, null, null);
            //clear sync dirty flag
            cv.clear();
            cv.put(Events._SYNC_DIRTY, 0);
            mCR.update(ContentUris.withAppendedId(EVENTS_URI, tid), cv, null, null);
            Log.d(TAG, "Updated " + uid);
        } else if (!newdevevs.containsKey(uid)) {
            euri = mCR.insert(EVENTS_URI, cv);
            Log.d(TAG, "Inserted " + uid);
        }
    }
    // the remaining events in local and dirty event list are no longer on the server. So remove them.
    for (String uid : localevs.keySet())
        removeLocalEvent(localevs.get(uid));

    //XXX Is this possible?
    /*
    for (String uid: dirtyevs.keySet ())
    removeLocalEvent (dirtyevs[uid]);
     */
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

private static void deleteContact(Context context, long rawContactId, BatchOperation batchOperation) {
    batchOperation.add(ContactOperations
            .newDeleteCpo(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), true, true)
            .build());/* w w w  .ja  va 2s  . co  m*/
}

From source file:com.csipsimple.db.DBProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    int matched = URI_MATCHER.match(uri);
    String matchedTable = null;/*from  w w w .  j a v  a  2 s  .  c  om*/
    Uri baseInsertedUri = null;

    switch (matched) {
    case ACCOUNTS:
    case ACCOUNTS_ID:
        matchedTable = SipProfile.ACCOUNTS_TABLE_NAME;
        baseInsertedUri = SipProfile.ACCOUNT_ID_URI_BASE;
        break;
    case CALLLOGS:
    case CALLLOGS_ID:
        matchedTable = SipManager.CALLLOGS_TABLE_NAME;
        baseInsertedUri = SipManager.CALLLOG_ID_URI_BASE;
        break;
    case FILTERS:
    case FILTERS_ID:
        matchedTable = SipManager.FILTERS_TABLE_NAME;
        baseInsertedUri = SipManager.FILTER_ID_URI_BASE;
        break;
    case MESSAGES:
    case MESSAGES_ID:
        matchedTable = SipMessage.MESSAGES_TABLE_NAME;
        baseInsertedUri = SipMessage.MESSAGE_ID_URI_BASE;
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            SipProfileState ps = new SipProfileState();
            if (profilesStatus.containsKey(id)) {
                ContentValues currentValues = profilesStatus.get(id);
                ps.createFromContentValue(currentValues);
            }
            ps.createFromContentValue(initialValues);
            ContentValues cv = ps.getAsContentValue();
            cv.put(SipProfileState.ACCOUNT_ID, id);
            profilesStatus.put(id, cv);
            Log.d(THIS_FILE, "Added " + cv);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return uri;
    default:
        break;
    }

    if (matchedTable == null) {
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    ContentValues values;

    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    long rowId = db.insert(matchedTable, null, values);

    // If the insert succeeded, the row ID exists.
    if (rowId >= 0) {
        // TODO : for inserted account register it here

        Uri retUri = ContentUris.withAppendedId(baseInsertedUri, rowId);
        getContext().getContentResolver().notifyChange(retUri, null);

        if (matched == ACCOUNTS || matched == ACCOUNTS_ID) {
            broadcastAccountChange(rowId);
        }
        if (matched == CALLLOGS || matched == CALLLOGS_ID) {
            db.delete(SipManager.CALLLOGS_TABLE_NAME,
                    CallLog.Calls._ID + " IN " + "(SELECT " + CallLog.Calls._ID + " FROM "
                            + SipManager.CALLLOGS_TABLE_NAME + " ORDER BY " + CallLog.Calls.DEFAULT_SORT_ORDER
                            + " LIMIT -1 OFFSET 500)",
                    null);
        }
        if (matched == ACCOUNTS_STATUS || matched == ACCOUNTS_STATUS_ID) {
            broadcastRegistrationChange(rowId);
        }
        if (matched == FILTERS || matched == FILTERS_ID) {
            Filter.resetCache();
        }

        return retUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:com.app.uafeed.fragment.EntryFragment.java

private void refreshUI(Cursor entryCursor) {
    if (entryCursor != null) {
        String feedTitle = entryCursor.isNull(mFeedNamePos) ? entryCursor.getString(mFeedUrlPos)
                : entryCursor.getString(mFeedNamePos);
        BaseActivity activity = (BaseActivity) getActivity();
        activity.setTitle(feedTitle);//from   ww  w.  j a v  a  2 s  .c  o m

        byte[] iconBytes = entryCursor.getBlob(mFeedIconPos);
        Bitmap bitmap = UiUtils.getScaledBitmap(iconBytes, 24);
        if (bitmap != null) {
            activity.getActionBar().setIcon(new BitmapDrawable(getResources(), bitmap));
        } else {
            activity.getActionBar().setIcon(R.drawable.icon);
        }

        mFavorite = entryCursor.getInt(mIsFavoritePos) == 1;
        activity.invalidateOptionsMenu();

        // Listen the mobilizing task
        boolean isRefreshing = FetcherService.hasTasks(mEntriesIds[mCurrentPagerPos]);
        activity.getProgressBar().setVisibility(isRefreshing ? View.VISIBLE : View.GONE);

        // Mark the article as read
        if (entryCursor.getInt(mIsReadPos) != 1) {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getReadContentValues(), null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }).start();
        }
    }
}

From source file:com.android.mms.rcs.FavoriteDetailActivity.java

private Uri[] buildUris(final Set<String> keySet, final int newPickRecipientsCount) {
    Uri[] newUris = new Uri[newPickRecipientsCount];
    Iterator<String> it = keySet.iterator();
    int i = 0;/*  w  ww  . j a  v  a 2  s .c om*/
    while (it.hasNext()) {
        String id = it.next();
        newUris[i++] = ContentUris.withAppendedId(Phone.CONTENT_URI, Integer.parseInt(id));
        if (i == newPickRecipientsCount) {
            break;
        }
    }
    return newUris;
}

From source file:com.tct.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *//*from ww w .ja va2  s . com*/
public static long saveAttachment(Context context, InputStream in, Attachment attachment) {
    final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    final ContentValues cv = new ContentValues();
    final long attachmentId = attachment.mId;
    final long accountId = attachment.mAccountKey;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    String contentUri = null;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    String realUri = null; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD
    long size = 0;

    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.UIPROVIDER_ATTACHMENTDESTINATION_CACHE) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment when attachment destination is cache",
                    "attachment.size:" + attachment.mSize);
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment to storage",
                    "attachment.size:" + attachment.mSize);
            if (TextUtils.isEmpty(attachment.mFileName)) {
                // TODO: This will prevent a crash but does not surface the underlying problem
                // to the user correctly.
                LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId);
                throw new IOException("Can't save an attachment with no name");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
            String exchange = "com.tct.exchange";
            if (exchange.equals(context.getPackageName()) && !PermissionUtil
                    .checkPermissionAndLaunchExplain(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                throw new IOException("Can't save an attachment due to no Storage permission");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();
            realUri = "file://" + absolutePath; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            final String mimeType = TextUtils.isEmpty(attachment.mMimeType) ? "application/octet-stream"
                    : attachment.mMimeType;

            try {
                DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_S
                //Note: should use media scanner, it will allow update the
                //media provider uri column in download manager's database.
                long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                        true /* use media scanner */, mimeType, absolutePath, size,
                        true /* show notification */);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_E
                contentUri = dm.getUriForDownloadedFile(id).toString();
            } catch (final IllegalArgumentException e) {
                LogUtils.d(LogUtils.TAG, e, "IAE from DownloadManager while saving attachment");
                throw new IOException(e);
            }
        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_SAVED);
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
        if (realUri != null) {
            cv.put(AttachmentColumns.REAL_URI, realUri);
        }
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
    } catch (IOException e) {
        LogUtils.e(Logging.LOG_TAG, e, "Fail to save attachment to storage!");
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null && attachment.mContentId.length() > 0) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_S
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_S
            String srcContentUri = " src=\"" + contentUri + "\"";
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_E
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_E
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S
            try {
                html = html.replaceAll(contentIdRe, srcContentUri);
            } catch (PatternSyntaxException e) {
                LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern");
            }
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E
            cv.put(BodyColumns.HTML_CONTENT, html);
            Body.updateBodyWithMessageId(context, attachment.mMessageKey, cv);
            Body.restoreBodyHtmlWithMessageId(context, attachment.mMessageKey);
        }
    }
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    return size;
}

From source file:com.jefftharris.passwdsafe.file.PasswdFileUri.java

/** Resolve sync provider information */
private void resolveSyncProvider(long providerId, ContentResolver cr) {
    Uri providerUri = ContentUris.withAppendedId(PasswdSafeContract.Providers.CONTENT_URI, providerId);
    Cursor providerCursor = cr.query(providerUri, PasswdSafeContract.Providers.PROJECTION, null, null, null);
    try {/* w  w  w .  ja v  a2  s  . c o m*/
        if ((providerCursor != null) && providerCursor.moveToFirst()) {
            String typeStr = providerCursor.getString(PasswdSafeContract.Providers.PROJECTION_IDX_TYPE);
            try {
                itsSyncType = ProviderType.valueOf(typeStr);
                itsTitle = providerCursor.getString(PasswdSafeContract.Providers.PROJECTION_IDX_ACCT);
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "Unknown provider type: " + typeStr);
            }
        }
    } finally {
        if (providerCursor != null) {
            providerCursor.close();
        }
    }
}

From source file:org.mythtv.service.dvr.v26.RecordedHelperV26.java

private void processProgramGroups(final Context context, final LocationProfile locationProfile,
        Program[] programs) throws RemoteException, OperationApplicationException {
    Log.v(TAG, "processProgramGroups : enter");

    if (null == context)
        throw new RuntimeException("RecordedHelperV26 is not initialized");

    Map<String, ProgramGroup> programGroups = new TreeMap<String, ProgramGroup>();
    for (Program program : programs) {

        if (null != program.getRecording()) {

            if (null != program.getRecording().getRecGroup()
                    && !"livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                    && !"deleted".equalsIgnoreCase(program.getRecording().getRecGroup())) {
                String cleaned = ArticleCleaner.clean(program.getTitle());
                if (!programGroups.containsKey(cleaned)) {

                    ProgramGroup programGroup = new ProgramGroup();
                    programGroup.setTitle(program.getTitle());
                    programGroup.setCategory(program.getCategory());
                    programGroup.setInetref(program.getInetref());
                    programGroup.setSort(0);

                    programGroups.put(cleaned, programGroup);
                }// w  w w .  j  a va  2s.  c  o m

            }

        }

    }

    int processed = -1;
    int count = 0;

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    Log.v(TAG, "processProgramGroups : adding 'All' program group in programGroups");
    ProgramGroup all = new ProgramGroup(null, "All", "All", "All", "", 1);
    programGroups.put(all.getProgramGroup(), all);

    String[] programGroupProjection = new String[] { ProgramGroupConstants._ID };
    String programGroupSelection = ProgramGroupConstants.FIELD_PROGRAM_GROUP + " = ?";

    programGroupSelection = appendLocationHostname(context, locationProfile, programGroupSelection, null);

    for (String key : programGroups.keySet()) {
        Log.v(TAG, "processProgramGroups : processing programGroup '" + key + "'");

        ProgramGroup programGroup = programGroups.get(key);

        ContentValues programValues = convertProgramGroupToContentValues(locationProfile, programGroup);
        Cursor programGroupCursor = context.getContentResolver().query(ProgramGroupConstants.CONTENT_URI,
                programGroupProjection, programGroupSelection, new String[] { key }, null);
        if (programGroupCursor.moveToFirst()) {

            Long id = programGroupCursor
                    .getLong(programGroupCursor.getColumnIndexOrThrow(ProgramGroupConstants._ID));
            ops.add(ContentProviderOperation
                    .newUpdate(ContentUris.withAppendedId(ProgramGroupConstants.CONTENT_URI, id))
                    .withValues(programValues).withYieldAllowed(true).build());

        } else {

            ops.add(ContentProviderOperation.newInsert(ProgramGroupConstants.CONTENT_URI)
                    .withValues(programValues).withYieldAllowed(true).build());
        }
        programGroupCursor.close();
        count++;

        if (count > 100) {
            Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

            processBatch(context, ops, processed, count);
        }

    }

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    Log.v(TAG, "processProgramGroups : remove deleted program groups");
    ops = new ArrayList<ContentProviderOperation>();

    DateTime lastModified = new DateTime();
    lastModified = lastModified.minusHours(1);

    String deleteProgramGroupSelection = ProgramGroupConstants.FIELD_LAST_MODIFIED_DATE + " < ?";
    String[] deleteProgramGroupArgs = new String[] { String.valueOf(lastModified.getMillis()) };

    deleteProgramGroupSelection = appendLocationHostname(context, locationProfile, deleteProgramGroupSelection,
            ProgramGroupConstants.TABLE_NAME);

    ops.add(ContentProviderOperation.newDelete(ProgramGroupConstants.CONTENT_URI)
            .withSelection(deleteProgramGroupSelection, deleteProgramGroupArgs).withYieldAllowed(true).build());

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    Log.v(TAG, "processProgramGroups : exit");
}