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:de.nware.app.hsDroid.provider.onlineService2Provider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    if (mUriMatcher.match(uri) != EXAMS) {
        throw new IllegalArgumentException("Unbekannte URI " + uri);
    }/*from   ww w  .  j a v  a  2  s.  co  m*/

    ContentValues contentValues;
    if (initialValues != null) {
        contentValues = new ContentValues(initialValues);
    } else {
        contentValues = new ContentValues();
    }
    if (mOpenHelper == null) {
        Log.d(TAG, "mOpenHelper NULL");
    }
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    long rowID = db.insert(mOpenHelper.getTableName(), ExamsCol.EXAMNAME, contentValues);
    if (rowID > 0) {
        Uri examsUri = ContentUris.withAppendedId(ExamsCol.CONTENT_URI, rowID);
        getContext().getContentResolver().notifyChange(examsUri, null); // Observer?
        return examsUri;
    }
    throw new SQLException("Konnte row nicht zu " + uri + " hinzufgen");
}

From source file:com.example.rapha.transpotsystem.RegisterActivity.java

@TargetApi(19)
private void handleImageOnKitKat(int requestCode, Intent data) {
    String imagePath = null;/* w w  w.j a  v a  2  s.c  o m*/
    Uri uri = data.getData();
    if (DocumentsContract.isDocumentUri(this, uri)) {
        String docId = DocumentsContract.getDocumentId(uri);
        if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
            String id = docId.split(":")[1];
            String selection = MediaStore.Images.Media._ID + "=" + id;
            imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
        } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
            Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(docId));
            imagePath = getImagePath(contentUri, null);
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        imagePath = getImagePath(uri, null);
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        imagePath = uri.getPath();
    }
    displayImage(requestCode, imagePath);

}

From source file:com.android.contacts.DynamicShortcuts.java

private Bitmap getContactPhoto(long id) {
    final InputStream photoStream = Contacts.openContactPhotoInputStream(mContext.getContentResolver(),
            ContentUris.withAppendedId(Contacts.CONTENT_URI, id), true);

    if (photoStream == null)
        return null;
    try {/*from  www  .  j a  v  a  2  s  . c  om*/
        final Bitmap bitmap = decodeStreamForShortcut(photoStream);
        photoStream.close();
        return bitmap;
    } catch (IOException e) {
        Log.e(TAG, "Failed to decode contact photo for shortcut. ID=" + id, e);
        return null;
    } finally {
        try {
            photoStream.close();
        } catch (IOException e) {
            // swallow
        }
    }
}

From source file:com.akop.bach.fragment.playstation.GamesFragment.java

@Override
public void onImageReady(long id, Object param, Bitmap bmp) {
    super.onImageReady(id, param, bmp);

    if (getActivity() != null) {
        getActivity().getContentResolver().notifyChange(ContentUris.withAppendedId(Games.CONTENT_URI, id),
                null);/*  www.j av a 2  s. co m*/
    }
}

From source file:com.xorcode.andtweet.TweetListActivity.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    super.onContextItemSelected(item);
    AdapterView.AdapterContextMenuInfo info;
    try {/*from   ww  w. ja va2s  .c  o  m*/
        info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    } catch (ClassCastException e) {
        Log.e(TAG, "bad menuInfo", e);
        return false;
    }

    mCurrentId = info.id;

    Uri uri;
    Cursor c;

    switch (item.getItemId()) {
    case CONTEXT_MENU_ITEM_REPLY:
        uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id);
        c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID }, null, null, null);
        try {
            c.moveToFirst();
            String reply = "@" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)) + " ";
            long replyId = c.getLong(c.getColumnIndex(Tweets._ID));
            mTweetEditor.startEditing(reply, replyId);
        } catch (Exception e) {
            Log.e(TAG, "onContextItemSelected: " + e.toString());
            return false;
        } finally {
            if (c != null && !c.isClosed())
                c.close();
        }
        return true;

    case CONTEXT_MENU_ITEM_RETWEET:
        uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id);
        c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID, Tweets.MESSAGE }, null,
                null, null);
        try {
            c.moveToFirst();

            StringBuilder message = new StringBuilder();
            String reply = "RT @" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)) + " ";
            message.append(reply);
            CharSequence text = c.getString(c.getColumnIndex(Tweets.MESSAGE));
            int len = 140 - reply.length() - 3;
            if (text.length() < len) {
                len = text.length();
            }
            message.append(text, 0, len);
            if (message.length() == 137) {
                message.append("...");
            }
            mTweetEditor.startEditing(message.toString(), 0);
        } catch (Exception e) {
            Log.e(TAG, "onContextItemSelected: " + e.toString());
            return false;
        } finally {
            if (c != null && !c.isClosed())
                c.close();
        }
        return true;

    case CONTEXT_MENU_ITEM_DESTROY_STATUS:
        sendCommand(new CommandData(CommandEnum.DESTROY_STATUS, mCurrentId));
        return true;

    case CONTEXT_MENU_ITEM_FAVORITE:
        sendCommand(new CommandData(CommandEnum.CREATE_FAVORITE, mCurrentId));
        return true;

    case CONTEXT_MENU_ITEM_DESTROY_FAVORITE:
        sendCommand(new CommandData(CommandEnum.DESTROY_FAVORITE, mCurrentId));
        return true;

    case CONTEXT_MENU_ITEM_SHARE:
        uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id);
        c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID, Tweets.MESSAGE }, null,
                null, null);
        try {
            c.moveToFirst();

            StringBuilder subject = new StringBuilder();
            StringBuilder text = new StringBuilder();
            String message = c.getString(c.getColumnIndex(Tweets.MESSAGE));

            subject.append(getText(R.string.button_create_tweet));
            subject.append(" - " + message);
            int maxlength = 80;
            if (subject.length() > maxlength) {
                subject.setLength(maxlength);
                // Truncate at the last space
                subject.setLength(subject.lastIndexOf(" "));
                subject.append("...");
            }

            text.append(message);
            text.append("\n-- \n" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)));
            text.append("\n URL: " + "http://twitter.com/" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID))
                    + "/status/" + c.getString(c.getColumnIndex(Tweets._ID)));

            Intent share = new Intent(android.content.Intent.ACTION_SEND);
            share.setType("text/plain");
            share.putExtra(Intent.EXTRA_SUBJECT, subject.toString());
            share.putExtra(Intent.EXTRA_TEXT, text.toString());
            startActivity(Intent.createChooser(share, getText(R.string.menu_item_share)));

        } catch (Exception e) {
            Log.e(TAG, "onContextItemSelected: " + e.toString());
            return false;
        } finally {
            if (c != null && !c.isClosed())
                c.close();
        }
        return true;

    case CONTEXT_MENU_ITEM_UNFOLLOW:
    case CONTEXT_MENU_ITEM_BLOCK:
    case CONTEXT_MENU_ITEM_DIRECT_MESSAGE:
    case CONTEXT_MENU_ITEM_PROFILE:
        Toast.makeText(this, R.string.unimplemented, Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}

From source file:com.android.contacts.preference.DisplayOptionsPreferenceFragment.java

@Override
public boolean onPreferenceClick(Preference p) {
    final String prefKey = p.getKey();

    if (KEY_ABOUT.equals(prefKey)) {
        ((ContactsPreferenceActivity) getActivity()).showAboutFragment();
        return true;
    } else if (KEY_IMPORT.equals(prefKey)) {
        ImportDialogFragment.show(getFragmentManager());
        return true;
    } else if (KEY_EXPORT.equals(prefKey)) {
        ExportDialogFragment.show(getFragmentManager(), ContactsPreferenceActivity.class,
                ExportDialogFragment.EXPORT_MODE_ALL_CONTACTS);
        return true;
    } else if (KEY_MY_INFO.equals(prefKey)) {
        if (mHasProfile) {
            final Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, mProfileContactId);
            ImplicitIntentsUtil.startQuickContact(getActivity(), uri, ScreenType.ME_CONTACT);
        } else {//from  ww w .  j a v  a  2s  .c  o  m
            final Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
            intent.putExtra(mNewLocalProfileExtra, true);
            ImplicitIntentsUtil.startActivityInApp(getActivity(), intent);
        }
        return true;
    } else if (KEY_ACCOUNTS.equals(prefKey)) {
        ImplicitIntentsUtil.startActivityOutsideApp(getContext(),
                ImplicitIntentsUtil.getIntentForAddingAccount());
        return true;
    } else if (KEY_BLOCKED_NUMBERS.equals(prefKey)) {
        final Intent intent = TelecomManagerUtil.createManageBlockedNumbersIntent(
                (TelecomManager) getContext().getSystemService(Context.TELECOM_SERVICE));
        startActivity(intent);
        return true;
    } else if (KEY_CUSTOM_CONTACTS_FILTER.equals(prefKey)) {
        final ContactListFilter filter = ContactListFilterController.getInstance(getContext()).getFilter();
        AccountFilterUtil.startAccountFilterActivityForResult(this, REQUEST_CODE_CUSTOM_CONTACTS_FILTER,
                filter);
    }
    return false;
}

From source file:com.carlrice.reader.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);//  w  w w .  j  av  a 2s .c  o m

        byte[] iconBytes = entryCursor.getBlob(mFeedIconPos);
        Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
        UiUtils.getFaviconPalette(bitmap, mToolbarPaletteListener);

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

        // Listen the mobilizing task
        if (FetcherService.hasMobilizationTask(mEntriesIds[mCurrentPagerPos])) {
            showSwipeProgress();

            // If the service is not started, start it here to avoid an infinite loading
            if (!PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false)) {
                Application.context().startService(new Intent(Application.context(), FetcherService.class)
                        .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
            }
        } else {
            hideSwipeProgress();
        }

        // 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 = Application.context().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.flym.dennikn.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   w w w .  j a  v a2s. com

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

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

        // Listen the mobilizing task
        if (FetcherService.hasMobilizationTask(mEntriesIds[mCurrentPagerPos])) {
            showSwipeProgress();

            // If the service is not started, start it here to avoid an infinite loading
            if (!PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false)) {
                MainApplication.getContext()
                        .startService(new Intent(MainApplication.getContext(), FetcherService.class)
                                .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
            }
        } else {
            hideSwipeProgress();
        }

        // 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.csipsimple.ui.favorites.FavAdapter.java

private void showDialogForGroupSelection(final Context context, final Long profileId, final String groupName) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(R.string.set_android_group);
    final Cursor choiceCursor = ContactsWrapper.getInstance().getGroups(context);
    int selectedIndex = -1;
    if (choiceCursor != null) {
        if (choiceCursor.moveToFirst()) {
            int i = 0;
            int colIdx = choiceCursor.getColumnIndex(ContactsWrapper.FIELD_GROUP_NAME);
            do {/*www.ja  v  a 2 s .c  o  m*/
                String name = choiceCursor.getString(colIdx);
                if (!TextUtils.isEmpty(name) && name.equalsIgnoreCase(groupName)) {
                    selectedIndex = i;
                    break;
                }
                i++;
            } while (choiceCursor.moveToNext());
        }
    }
    builder.setSingleChoiceItems(choiceCursor, selectedIndex, ContactsWrapper.FIELD_GROUP_NAME,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (choiceCursor != null) {
                        choiceCursor.moveToPosition(which);
                        String name = choiceCursor
                                .getString(choiceCursor.getColumnIndex(ContactsWrapper.FIELD_GROUP_NAME));
                        ContentValues cv = new ContentValues();
                        cv.put(SipProfile.FIELD_ANDROID_GROUP, name);
                        context.getContentResolver().update(
                                ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, profileId), cv, null,
                                null);
                        choiceCursor.close();
                    }
                    dialog.dismiss();
                }
            });

    builder.setCancelable(true);
    builder.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (choiceCursor != null) {
                choiceCursor.close();
            }
            dialog.dismiss();
        }
    });
    builder.setOnCancelListener(new OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (choiceCursor != null) {
                choiceCursor.close();
            }
        }
    });
    final Dialog dialog = builder.create();
    dialog.show();
}

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

/**
 * Save the attachment to its final resting place (cache or sd card)
 *//*from   w w  w  .j a v a 2  s.c om*/
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri;
    long size;
    try {
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            File saveIn = getAttachmentDirectory(context, accountId);
            if (!saveIn.exists()) {
                saveIn.mkdirs();
            }
            File file = getAttachmentFilename(context, accountId, attachmentId);
            file.createNewFile();
            size = copyFile(in, file);
            contentUri = getAttachmentUri(accountId, attachmentId).toString();
        } else if (Utility.isExternalStorageMounted()) {
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, file);
            String absolutePath = file.getAbsolutePath();

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

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            Log.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.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

}