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.android.mms.ui.MessageUtils.java

private static String getNotificationIndDetails(Context context, MessageItem msgItem) {
    /// @}/* w w w .  j  ava  2  s  . c o m*/
    StringBuilder details = new StringBuilder();
    Resources res = context.getResources();

    // / M: Code analyze 027, new feature, to improve the performance of
    // Mms. @{
    Uri uri = ContentUris.withAppendedId(Mms.CONTENT_URI, msgItem.mMsgId);
    /// @}
    NotificationInd nInd;

    try {
        // / M: Code analyze 027, new feature, to improve the performance of
        // Mms. @{
        nInd = (NotificationInd) PduPersister.getPduPersister(context).load(uri);
        /// @}
    } catch (MmsException e) {
        Log.e(TAG, "Failed to load the message: " + uri, e);
        return context.getResources().getString(R.string.cannot_get_details);
    }

    // Message Type: Mms Notification.
    details.append(res.getString(R.string.message_type_label));
    details.append(res.getString(R.string.multimedia_notification));

    /// M: Code analyze 026, new feature, show the service center number.
    // @{
    details.append('\n');
    details.append(res.getString(R.string.service_center_label));
    details.append(!TextUtils.isEmpty(msgItem.mServiceCenter) ? msgItem.mServiceCenter : "");
    /// @}

    // From: ***
    String from = extractEncStr(context, nInd.getFrom());
    details.append('\n');
    details.append(res.getString(R.string.from_label));
    details.append(!TextUtils.isEmpty(from) ? from : res.getString(R.string.hidden_sender_address));

    // Date: ***
    details.append('\n');
    details.append(res.getString(R.string.expire_on,
            MessageUtils.formatTimeStampString(context, nInd.getExpiry() * 1000L, true)));

    // Subject: ***
    details.append('\n');
    details.append(res.getString(R.string.subject_label));

    EncodedStringValue subject = nInd.getSubject();
    if (subject != null) {
        details.append(subject.getString());
    }

    // Message class: Personal/Advertisement/Infomational/Auto
    details.append('\n');
    details.append(res.getString(R.string.message_class_label));
    details.append(new String(nInd.getMessageClass()));

    // Message size: *** KB
    details.append('\n');
    details.append(res.getString(R.string.message_size_label));
    details.append(String.valueOf((nInd.getMessageSize() + 1023) / 1024));
    details.append(context.getString(R.string.kilobyte));

    return details.toString();
}

From source file:com.hhunj.hhudata.ForegroundService.java

private String updatedb(List<SearchBookContentsResult> items) {

    String sMessage = "";
    ContentResolver resolver = getApplicationContext().getContentResolver();

    ContentValues values = new ContentValues();

    for (int i = 0; i < items.size(); i++) {

        SearchBookContentsResult res = items.get(i);
        if (res == null)
            continue;
        long stationid = Long.parseLong(res.getPageNumber());

        values.put(NotePad.Notes.TITLE, res.getName());
        values.put(NotePad.Notes.NOTE, "");

        values.put(NotePad.Notes.LONGITUTE, 108.0);
        values.put(NotePad.Notes.LATITUDE, 32.0);
        values.put(NotePad.Notes.SPEED, 55);
        values.put(NotePad.Notes.ALTITUDE, 55);

        values.put(NotePad.Notes.CREATEDDATE, res.getRectime().getTime());

        values.put(NotePad.Notes._ID, stationid);// id

        Uri urlNote = NotePad.Notes.CONTENT_URI;

        Uri myUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, stationid);

        //?????//from   ww w . j  av  a  2s. co  m
        Cursor cur = resolver.query(myUri, NotePad.Notes.PROJECTION, null, null, null);
        if (cur == null) {
            // 
        }
        if (cur != null && cur.moveToFirst()) {
            long id = cur.getLong(NotePad.Notes._ID_COLUMN);
            Date oldtime = new Date(cur.getLong(cur.getColumnIndex(NotePad.Notes.CREATEDDATE)));
            boolean oldalarm = (cur.getInt(NotePad.Notes.ALARM_COLUMN) == 0) ? false : true;

            long dif = (res.getRectime().getTime() - oldtime.getTime()) / (60 * 1000);

            // 
            dif = ((new Date()).getTime() - oldtime.getTime()) / (60 * 1000);
            boolean newalarm = false;//
            if (dif > m_alamspan) {
                // ...
                if (oldalarm == false) {
                    Log.w(TAG, "over time err--------");
                    // String phoneNumber ="13338620269";
                    sMessage += "---" + id + "---";
                    newalarm = true;
                } else {
                    newalarm = true;
                }

            }

            values.put(NotePad.Notes.ALARM, newalarm);
            int count = resolver.update(myUri, values, null, null);
            if (count == 0) {

            }

        } else {
            values.put(NotePad.Notes.ALARM, false);
            try {
                myUri = resolver.insert(urlNote, values);
            } catch (IllegalArgumentException e) {
                throw e;
            } catch (SQLException e2) {
                int aa = 0;
                throw e2;
            }
        }
    }
    return sMessage;
}

From source file:com.almalence.googsharing.Thumbnail.java

private static Media getLastVideoThumbnail(ContentResolver resolver) {

    Media internalMedia = null;//from w ww . j  ava2  s  .  c om
    Media externalMedia = null;

    String name = getName();

    try {
        Uri baseUri = Video.Media.INTERNAL_CONTENT_URI;

        Uri query = baseUri.buildUpon().appendQueryParameter("limit", "1").build();
        String[] projection = new String[] { VideoColumns._ID, VideoColumns.DATA, VideoColumns.DATE_TAKEN };

        String selection = VideoColumns.DATA + " like '%" + name + "%' AND " + VideoColumns.MIME_TYPE
                + "='video/mp4'";
        String order = VideoColumns.DATE_TAKEN + " DESC," + VideoColumns._ID + " DESC";

        Cursor cursor = null;

        try {
            cursor = resolver.query(query, projection, selection, null, order);
            if (cursor != null && cursor.moveToFirst()) {
                final long id = cursor.getLong(0);
                internalMedia = new Media(id, 0, cursor.getLong(2), ContentUris.withAppendedId(baseUri, id));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } catch (Exception e) {

    }

    try {
        Uri baseUri = Video.Media.EXTERNAL_CONTENT_URI;
        Uri query = baseUri.buildUpon().appendQueryParameter("limit", "1").build();
        String[] projection = new String[] { VideoColumns._ID, VideoColumns.DATA, VideoColumns.DATE_TAKEN };

        String selection = VideoColumns.DATA + " like '%" + name + "%' AND " + VideoColumns.MIME_TYPE
                + "='video/mp4'";
        String order = VideoColumns.DATE_TAKEN + " DESC," + VideoColumns._ID + " DESC";

        Cursor cursor = null;

        try {
            cursor = resolver.query(query, projection, selection, null, order);
            if (cursor != null && cursor.moveToFirst()) {
                final long id = cursor.getLong(0);
                externalMedia = new Media(id, 0, cursor.getLong(2), ContentUris.withAppendedId(baseUri, id));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } catch (Exception e) {

    }

    if (internalMedia == null) {
        return externalMedia;
    } else if (externalMedia == null) {
        return internalMedia;
    } else {
        return internalMedia.dateTaken > externalMedia.dateTaken ? internalMedia : externalMedia;
    }
}

From source file:com.shafiq.myfeedle.core.MyfeedleService.java

private void start(Intent intent) {
    if (intent != null) {
        String action = intent.getAction();
        Log.d(TAG, "action:" + action);
        if (ACTION_REFRESH.equals(action)) {
            if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS))
                putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1);
            else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 1);
            else if (intent.getData() != null)
                putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1);
            else//w w  w  .ja v a  2s . c om
                putValidatedUpdates(null, 0);
        } else if (LauncherIntent.Action.ACTION_READY.equals(action)) {
            if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION)
                    && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1);
                int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                // check if the scrollable needs to be built
                Cursor widget = this.getContentResolver().query(Widgets.getContentUri(MyfeedleService.this),
                        new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?",
                        new String[] { Integer.toString(appWidgetId) }, null);
                if (widget.moveToFirst()) {
                    if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) {
                        ContentValues values = new ContentValues();
                        values.put(Widgets.SCROLLABLE, scrollableVersion);
                        // set the scrollable version
                        this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values,
                                Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                    } else
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                } else {
                    ContentValues values = new ContentValues();
                    values.put(Widgets.SCROLLABLE, scrollableVersion);
                    // set the scrollable version
                    this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values,
                            Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                    putValidatedUpdates(new int[] { appWidgetId }, 1);
                }
                widget.close();
            } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                // requery
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 0);
            }
        } else if (SMS_RECEIVED.equals(action)) {
            // parse the sms, and notify any widgets which have sms enabled
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdus.length; i++) {
                SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
                AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() {

                    @Override
                    protected int[] doInBackground(SmsMessage... msg) {
                        // check if SMS is enabled anywhere
                        Cursor widgets = getContentResolver().query(
                                Widget_accounts_view.getContentUri(MyfeedleService.this),
                                new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET,
                                        Widget_accounts_view.ACCOUNT },
                                Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) },
                                null);
                        int[] appWidgetIds = new int[widgets.getCount()];
                        if (widgets.moveToFirst()) {
                            // insert this message to the statuses db and requery scrollable/rebuild widget
                            // check if this is a contact
                            String phone = msg[0].getOriginatingAddress();
                            String friend = phone;
                            byte[] profile = null;
                            Uri content_uri = null;
                            // unknown numbers crash here in the emulator
                            Cursor phones = getContentResolver().query(
                                    Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                                            Uri.encode(phone)),
                                    new String[] { ContactsContract.PhoneLookup._ID }, null, null, null);
                            if (phones.moveToFirst())
                                content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
                                        phones.getLong(0));
                            else {
                                Cursor emails = getContentResolver().query(
                                        Uri.withAppendedPath(
                                                ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI,
                                                Uri.encode(phone)),
                                        new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null,
                                        null);
                                if (emails.moveToFirst())
                                    content_uri = ContentUris.withAppendedId(
                                            ContactsContract.Contacts.CONTENT_URI, emails.getLong(0));
                                emails.close();
                            }
                            phones.close();
                            if (content_uri != null) {
                                // load contact
                                Cursor contacts = getContentResolver().query(content_uri,
                                        new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null,
                                        null);
                                if (contacts.moveToFirst())
                                    friend = contacts.getString(0);
                                contacts.close();
                                profile = getBlob(ContactsContract.Contacts
                                        .openContactPhotoInputStream(getContentResolver(), content_uri));
                            }
                            long accountId = widgets.getLong(2);
                            long id;
                            ContentValues values = new ContentValues();
                            values.put(Entities.ESID, phone);
                            values.put(Entities.FRIEND, friend);
                            values.put(Entities.PROFILE, profile);
                            values.put(Entities.ACCOUNT, accountId);
                            Cursor entity = getContentResolver().query(
                                    Entities.getContentUri(MyfeedleService.this), new String[] { Entities._ID },
                                    Entities.ACCOUNT + "=? and " + Entities.ESID + "=?",
                                    new String[] { Long.toString(accountId), mMyfeedleCrypto.Encrypt(phone) },
                                    null);
                            if (entity.moveToFirst()) {
                                id = entity.getLong(0);
                                getContentResolver().update(Entities.getContentUri(MyfeedleService.this),
                                        values, Entities._ID + "=?", new String[] { Long.toString(id) });
                            } else
                                id = Long.parseLong(getContentResolver()
                                        .insert(Entities.getContentUri(MyfeedleService.this), values)
                                        .getLastPathSegment());
                            entity.close();
                            values.clear();
                            Long created = msg[0].getTimestampMillis();
                            values.put(Statuses.CREATED, created);
                            values.put(Statuses.ENTITY, id);
                            values.put(Statuses.MESSAGE, msg[0].getMessageBody());
                            values.put(Statuses.SERVICE, SMS);
                            while (!widgets.isAfterLast()) {
                                int widget = widgets.getInt(1);
                                appWidgetIds[widgets.getPosition()] = widget;
                                // get settings
                                boolean time24hr = true;
                                int status_bg_color = Myfeedle.default_message_bg_color;
                                int profile_bg_color = Myfeedle.default_message_bg_color;
                                int friend_bg_color = Myfeedle.default_friend_bg_color;
                                boolean icon = true;
                                int status_count = Myfeedle.default_statuses_per_account;
                                int notifications = 0;
                                Cursor c = getContentResolver().query(
                                        Widgets_settings.getContentUri(MyfeedleService.this),
                                        new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                Widgets.FRIEND_BG_COLOR },
                                        Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        null);
                                if (!c.moveToFirst()) {
                                    c.close();
                                    c = getContentResolver().query(
                                            Widgets_settings.getContentUri(MyfeedleService.this),
                                            new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                    Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                    Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                    Widgets.FRIEND_BG_COLOR },
                                            Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                            new String[] { Integer.toString(widget),
                                                    Long.toString(Myfeedle.INVALID_ACCOUNT_ID) },
                                            null);
                                    if (!c.moveToFirst()) {
                                        c.close();
                                        c = getContentResolver().query(
                                                Widgets_settings.getContentUri(MyfeedleService.this),
                                                new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                        Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT,
                                                        Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS,
                                                        Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR },
                                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                                new String[] {
                                                        Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID),
                                                        Long.toString(Myfeedle.INVALID_ACCOUNT_ID) },
                                                null);
                                        if (!c.moveToFirst())
                                            initAccountSettings(MyfeedleService.this,
                                                    AppWidgetManager.INVALID_APPWIDGET_ID,
                                                    Myfeedle.INVALID_ACCOUNT_ID);
                                        if (widget != AppWidgetManager.INVALID_APPWIDGET_ID)
                                            initAccountSettings(MyfeedleService.this, widget,
                                                    Myfeedle.INVALID_ACCOUNT_ID);
                                    }
                                    initAccountSettings(MyfeedleService.this, widget, accountId);
                                }
                                if (c.moveToFirst()) {
                                    time24hr = c.getInt(0) == 1;
                                    status_bg_color = c.getInt(1);
                                    icon = c.getInt(2) == 1;
                                    status_count = c.getInt(3);
                                    if (c.getInt(4) == 1)
                                        notifications |= Notification.DEFAULT_SOUND;
                                    if (c.getInt(5) == 1)
                                        notifications |= Notification.DEFAULT_VIBRATE;
                                    if (c.getInt(6) == 1)
                                        notifications |= Notification.DEFAULT_LIGHTS;
                                    profile_bg_color = c.getInt(7);
                                    friend_bg_color = c.getInt(8);
                                }
                                c.close();
                                values.put(Statuses.CREATEDTEXT, Myfeedle.getCreatedText(created, time24hr));
                                // update the bg and icon
                                // create the status_bg
                                values.put(Statuses.STATUS_BG, createBackground(status_bg_color));
                                // friend_bg
                                values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color));
                                // profile_bg
                                values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color));
                                values.put(Statuses.ICON,
                                        icon ? getBlob(getResources(), map_icons[SMS]) : null);
                                // insert the message
                                values.put(Statuses.WIDGET, widget);
                                values.put(Statuses.ACCOUNT, accountId);
                                getContentResolver().insert(Statuses.getContentUri(MyfeedleService.this),
                                        values);
                                // check the status count, removing old sms
                                Cursor statuses = getContentResolver().query(
                                        Statuses.getContentUri(MyfeedleService.this),
                                        new String[] { Statuses._ID },
                                        Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        Statuses.CREATED + " desc");
                                if (statuses.moveToFirst()) {
                                    while (!statuses.isAfterLast()) {
                                        if (statuses.getPosition() >= status_count) {
                                            getContentResolver().delete(
                                                    Statuses.getContentUri(MyfeedleService.this),
                                                    Statuses._ID + "=?", new String[] { Long.toString(statuses
                                                            .getLong(statuses.getColumnIndex(Statuses._ID))) });
                                        }
                                        statuses.moveToNext();
                                    }
                                }
                                statuses.close();
                                if (notifications != 0)
                                    publishProgress(Integer.toString(notifications),
                                            friend + " sent a message");
                                widgets.moveToNext();
                            }
                        }
                        widgets.close();
                        return appWidgetIds;
                    }

                    @Override
                    protected void onProgressUpdate(String... updates) {
                        int notifications = Integer.parseInt(updates[0]);
                        if (notifications != 0) {
                            Notification notification = new Notification(R.drawable.notification, updates[1],
                                    System.currentTimeMillis());
                            notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1],
                                    PendingIntent.getActivity(MyfeedleService.this, 0,
                                            (Myfeedle.getPackageIntent(MyfeedleService.this,
                                                    MyfeedleNotifications.class)),
                                            0));
                            notification.defaults |= notifications;
                            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                    .notify(NOTIFY_ID, notification);
                        }
                    }

                    @Override
                    protected void onPostExecute(int[] appWidgetIds) {
                        // remove self from thread list
                        if (!mSMSLoaders.isEmpty())
                            mSMSLoaders.remove(this);
                        putValidatedUpdates(appWidgetIds, 0);
                    }

                };
                mSMSLoaders.add(smsLoader);
                smsLoader.execute(msg);
            }
        } else if (ACTION_PAGE_DOWN.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_DOWN, 0));
        else if (ACTION_PAGE_UP.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_UP, 0));
        else {
            // this might be a widget update from the widget refresh button
            int appWidgetId;
            try {
                appWidgetId = Integer.parseInt(action);
                putValidatedUpdates(new int[] { appWidgetId }, 1);
            } catch (NumberFormatException e) {
                Log.d(TAG, "unknown action:" + action);
            }
        }
    }
}

From source file:at.bitfire.davdroid.resource.LocalCollection.java

/** Enqueues removing the dirty flag from a locally-stored resource. Requires commit() to be effective! */
public void clearDirty(Resource resource) {
    pendingOperations.add(/*from   ww  w  . j  a v a2  s.  com*/
            ContentProviderOperation.newUpdate(ContentUris.withAppendedId(entriesURI(), resource.getLocalID()))
                    .withValue(entryColumnDirty(), 0).build());
}

From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java

private int deleteArtwork(@NonNull final Uri uri, final String selection, final String[] selectionArgs) {
    // Opens the database object in "write" mode.
    final SQLiteDatabase db = databaseHelper.getWritableDatabase();
    String finalWhere = selection;
    if (MuzeiProvider.uriMatcher.match(uri) == ARTWORK_ID) {
        finalWhere = MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " = "
                + uri.getLastPathSegment();
        // If there were additional selection criteria, append them to the final WHERE clause
        if (selection != null)
            finalWhere = finalWhere + " AND " + selection;
    }/*from  w w  w  . j a  v  a  2s.  c  o  m*/
    // We can't just simply delete the rows as that won't free up the space occupied by the
    // artwork image files associated with each row being deleted. Instead we have to query
    // and manually delete each artwork file
    String[] projection = new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID,
            MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI, MuzeiContract.Artwork.COLUMN_NAME_TOKEN };
    Cursor rowsToDelete = queryArtwork(uri, projection, finalWhere, selectionArgs,
            MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI);
    if (rowsToDelete == null) {
        return 0;
    }
    // First we build a list of IDs to be deleted. This will be used if we need to determine
    // if a given image URI needs to be deleted
    List<String> idsToDelete = new ArrayList<>();
    rowsToDelete.moveToFirst();
    while (!rowsToDelete.isAfterLast()) {
        idsToDelete.add(Long.toString(rowsToDelete.getLong(0)));
        rowsToDelete.moveToNext();
    }
    String notInDeleteIds = MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " NOT IN ("
            + TextUtils.join(",", idsToDelete) + ")";
    // Now we actually go through the list of rows to be deleted
    // and check if we can delete the artwork image file associated with each one
    rowsToDelete.moveToFirst();
    while (!rowsToDelete.isAfterLast()) {
        Uri artworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, rowsToDelete.getLong(0));
        String imageUri = rowsToDelete.getString(1);
        String token = rowsToDelete.getString(2);
        if (TextUtils.isEmpty(imageUri) && TextUtils.isEmpty(token)) {
            // An empty image URI and token means the artwork is unique to this specific row
            // so we can always delete it when the associated row is deleted
            File artwork = getCacheFileForArtworkUri(artworkUri);
            if (artwork != null && artwork.exists()) {
                artwork.delete();
            }
        } else if (TextUtils.isEmpty(imageUri)) {
            // Check if there are other rows using this same token that aren't
            // in the list of ids to delete
            Cursor otherArtwork = queryArtwork(MuzeiContract.Artwork.CONTENT_URI,
                    new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID },
                    MuzeiContract.Artwork.COLUMN_NAME_TOKEN + "=? AND " + notInDeleteIds,
                    new String[] { token }, null);
            if (otherArtwork == null) {
                continue;
            }
            if (otherArtwork.getCount() == 0) {
                // There's no non-deleted rows that reference this same artwork URI
                // so we can delete the artwork
                File artwork = getCacheFileForArtworkUri(artworkUri);
                if (artwork != null && artwork.exists()) {
                    artwork.delete();
                }
            }
            otherArtwork.close();
        } else {
            // Check if there are other rows using this same image URI that aren't
            // in the list of ids to delete
            Cursor otherArtwork = queryArtwork(MuzeiContract.Artwork.CONTENT_URI,
                    new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID },
                    MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI + "=? AND " + notInDeleteIds,
                    new String[] { imageUri }, null);
            if (otherArtwork == null) {
                continue;
            }
            if (otherArtwork.getCount() == 0) {
                // There's no non-deleted rows that reference this same artwork URI
                // so we can delete the artwork
                File artwork = getCacheFileForArtworkUri(artworkUri);
                if (artwork != null && artwork.exists()) {
                    artwork.delete();
                }
            }
            otherArtwork.close();
        }
        rowsToDelete.moveToNext();
    }
    rowsToDelete.close();
    int count = db.delete(MuzeiContract.Artwork.TABLE_NAME, finalWhere, selectionArgs);
    if (count > 0) {
        notifyChange(uri);
    }
    return count;
}

From source file:com.android.emailcommon.provider.EmailContent.java

static public int update(Context context, Uri baseUri, long id, ContentValues contentValues) {
    return context.getContentResolver().update(ContentUris.withAppendedId(baseUri, id), contentValues, null,
            null);//from w w w .  j  av  a  2 s .  com
}

From source file:edu.mit.mobile.android.locast.sync.AbsMediaSync.java

/**
 * Synchronize the media of the given castMedia. It will download or upload as needed.
 *
 * Blocks until the sync is complete.//from w ww  .  j av  a  2  s.  c  o  m
 *
 * @param castMediaDir
 *            a {@link CastMedia} item uri
 * @throws SyncException
 */
public void syncItemMedia(Uri castMediaDir) throws SyncException {

    final SyncableProvider provider = getSyncableProvider(castMediaDir);
    if (provider == null) {
        Log.e(TAG, "could not sync item media: could not get local binder for syncable provider");
        return;
    }

    if (DEBUG) {
        Log.d(TAG, "syncing " + castMediaDir);
    }

    final CastMedia castMedia = (CastMedia) provider.getWrappedContentItem(castMediaDir,
            mCr.query(castMediaDir, getCastMediaProjection(), null, null, null));

    final NotificationProgressListener downloadListener = new NotificationProgressListener(this,
            NotificationProgressListener.TYPE_DOWNLOAD, R.id.locast_core__sync_download);

    try {
        final int totalItems = castMedia.getCount();

        downloadListener.setTotalItems(totalItems);

        // cache the column numbers
        final int mediaUrlCol = castMedia.getColumnIndex(CastMedia.COL_MEDIA_URL);
        final int localUriCol = castMedia.getColumnIndex(CastMedia.COL_LOCAL_URL);
        final int idCol = castMedia.getColumnIndex(CastMedia._ID);
        final int mediaDirtyCol = castMedia.getColumnIndex(CastMedia.COL_MEDIA_DIRTY);

        while (castMedia.moveToNext()) {

            final boolean keepOffline = castMedia
                    .getInt(castMedia.getColumnIndex(CastMedia.COL_KEEP_OFFLINE)) != 0;

            final String mimeType = castMedia.getString(castMedia.getColumnIndex(CastMedia.COL_MIME_TYPE));

            final boolean isImage = (mimeType != null) && mimeType.startsWith("image/");

            // we don't need to sync this
            if ("text/html".equals(mimeType)) {
                return;
            }

            final Uri locMedia = castMedia.isNull(localUriCol) ? null
                    : Uri.parse(castMedia.getString(localUriCol));
            final String pubMedia = castMedia.getString(mediaUrlCol);
            final boolean hasLocMedia = locMedia != null && new File(locMedia.getPath()).exists();
            final boolean hasPubMedia = pubMedia != null && pubMedia.length() > 0;

            final String localThumb = castMedia.getString(castMedia.getColumnIndex(CastMedia.COL_THUMB_LOCAL));

            final Uri castMediaItem = ContentUris.withAppendedId(castMediaDir, castMedia.getLong(idCol));

            final boolean isLocalDirty = castMedia.isNull(mediaDirtyCol)
                    || castMedia.getInt(mediaDirtyCol) != 0;

            if (hasLocMedia && isLocalDirty) {
                if (DEBUG) {
                    Log.d(TAG, castMediaItem + " has local media and it's dirty");
                }

                final String uploadPath = castMedia
                        .getString(castMedia.getColumnIndex(CastMedia.COL_PUBLIC_URL));
                if (uploadPath == null) {
                    Log.w(TAG, "attempted to sync " + castMediaItem + " which has a null uploadPath");
                    return;
                }

                final Uri titledItem = getTitledItemForCastMedia(castMediaItem);
                final NotificationProgressListener uploadListener = new NotificationProgressListener(this,
                        NotificationProgressListener.TYPE_UPLOAD, titledItem.hashCode());

                try {
                    uploadMedia(uploadPath, castMediaItem, titledItem, mimeType, locMedia, uploadListener);
                    uploadListener.onTransfersSuccessful();
                } finally {
                    uploadListener.onAllTransfersComplete();
                }

            } else if (!hasLocMedia && hasPubMedia) {
                if (DEBUG) {
                    Log.d(TAG, castMediaItem + " doesn't have local media, but has public media url");
                }

                // only have a public copy, so download it and store locally.
                final Uri pubMediaUri = Uri.parse(pubMedia);
                final File destfile = getFilePath(pubMediaUri);

                // the following conditions indicate that the cast media should be downloaded.
                if (keepOffline || getKeepOffline(castMediaItem, castMedia)) {

                    final boolean anythingChanged = downloadMediaFile(pubMedia, destfile, castMediaItem,
                            downloadListener);

                    // the below is inverted from what seems logical, because
                    // downloadMediaFile()
                    // will actually update the castmedia if it downloads anything. We'll only
                    // be
                    // getting here if we don't have any local record of the file, so we should
                    // make
                    // the association by ourselves.
                    if (!anythingChanged) {
                        File thumb = null;
                        if (isImage && localThumb == null) {
                            thumb = destfile;
                        }
                        updateLocalFile(castMediaDir, destfile, thumb);
                        // disabled to avoid spamming the user with downloaded
                        // items.
                        // checkForMediaEntry(castMediaUri, pubMediaUri, mimeType);
                    }
                }
            } else {
                // ensure we tell the listener that we finished
                downloadListener.onTransferComplete(castMediaItem);
            }
        }
        downloadListener.onTransfersSuccessful();
    } finally {
        downloadListener.onAllTransfersComplete();
        castMedia.close();
    }

}

From source file:com.ternup.caddisfly.fragment.ResultFragment.java

private void displayResult() {

    String[] projection = { TestTable.TABLE_TEST + "." + TestTable.COLUMN_ID,
            TestTable.TABLE_TEST + "." + TestTable.COLUMN_DATE, TestTable.COLUMN_RESULT, TestTable.COLUMN_TYPE,
            TestTable.COLUMN_FOLDER, LocationTable.COLUMN_NAME, LocationTable.COLUMN_STREET,
            LocationTable.COLUMN_TOWN, LocationTable.COLUMN_CITY, LocationTable.COLUMN_STATE,
            LocationTable.COLUMN_COUNTRY, LocationTable.COLUMN_STREET, LocationTable.COLUMN_SOURCE };

    Log.d("Result", mId + " test");

    Uri uri = ContentUris.withAppendedId(TestContentProvider.CONTENT_URI, mId);
    Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
    cursor.moveToFirst();//from  www . ja v a  2s .c  o m

    mAddressText.setText(cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_NAME)) + ", "
            + cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_STREET)));

    mAddress2Text.setText(cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_TOWN)) + ", "
            + cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_CITY)));

    mAddress3Text.setText(cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_STATE)) + ", "
            + cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_COUNTRY)));

    if (mAddress2Text.getText().equals(", ")) {
        mAddress2Text.setVisibility(View.GONE);
    } else {
        mAddress2Text.setVisibility(View.VISIBLE);
    }
    if (mAddress3Text.getText().equals(", ")) {
        mAddress3Text.setVisibility(View.GONE);
    } else {
        mAddress3Text.setVisibility(View.VISIBLE);
    }
    String[] sourceArray = getResources().getStringArray(R.array.source_types);
    int sourceType = cursor.getInt(cursor.getColumnIndex(LocationTable.COLUMN_SOURCE));
    if (sourceType > -1) {
        mSourceText.setText(sourceArray[sourceType]);
        mSourceText.setVisibility(View.VISIBLE);
    } else {
        mSourceText.setVisibility(View.GONE);
    }
    Date date = new Date(cursor.getLong(cursor.getColumnIndex(TestTable.COLUMN_DATE)));
    SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy");
    DateFormat tf = android.text.format.DateFormat.getTimeFormat(getActivity()); // Gets system TF

    String dateString = df.format(date.getTime()) + ", " + tf.format(date.getTime());

    mTestType = DataHelper.getTestTitle(getActivity(),
            cursor.getInt(cursor.getColumnIndex(TestTable.COLUMN_TYPE)));
    mTestTypeId = cursor.getInt(cursor.getColumnIndex(TestTable.COLUMN_TYPE));

    mTitleView.setText(mTestType);
    mDateView.setText(dateString);

    Double resultPpm = cursor.getDouble(cursor.getColumnIndex(TestTable.COLUMN_RESULT));

    if (mTestTypeId == Globals.PH_INDEX) {
        mPpmText.setText("");
    } else {
        mPpmText.setText(R.string.ppm);
    }

    if (resultPpm < 0) {
        mResultTextView.setText("0.0");
        //mResultIcon.setVisibility(View.GONE);
        mPpmText.setVisibility(View.GONE);
    } else {
        mResultTextView.setText(String.format("%.2f", resultPpm));

        Context context = getActivity().getApplicationContext();

        int resourceAttribute;

        if (resultPpm <= Globals.FLUORIDE_MAX_DRINK) {
            resourceAttribute = R.attr.drink;
        } else if (resultPpm <= Globals.FLUORIDE_MAX_COOK) {
            resourceAttribute = R.attr.cook;
        } else if (resultPpm <= Globals.FLUORIDE_MAX_BATHE) {
            resourceAttribute = R.attr.bath;
        } else {
            resourceAttribute = R.attr.wash;
        }

        TypedArray a = context.getTheme().obtainStyledAttributes(
                ((MainApp) context.getApplicationContext()).CurrentTheme, new int[] { resourceAttribute });
        int attributeResourceId = a.getResourceId(0, 0);
        //mResultIcon.setImageResource(attributeResourceId);

        //mResultIcon.setVisibility(View.VISIBLE);
        mPpmText.setVisibility(View.VISIBLE);
    }

    cursor.close();
}

From source file:com.android.emailcommon.provider.EmailContent.java

static public int delete(Context context, Uri baseUri, long id) {
    return context.getContentResolver().delete(ContentUris.withAppendedId(baseUri, id), null, null);
}