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.applozic.mobicommons.file.FileUtils.java

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.<br>
 * <br>// ww w. j av a 2  s  .c o  m
 * Callers should check whether the path is local before assuming it
 * represents a local file.
 *
 * @param context The context.
 * @param uri     The Uri to query.
 * @author paulburke
 * @see #isLocal(String)
 * @see #getFile(android.content.Context, android.net.Uri)
 */

public static String getPath(final Context context, final Uri uri) {

    if (DEBUG)
        Log.d(TAG + " File -",
                "Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment() + ", Port: "
                        + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme: " + uri.getScheme()
                        + ", Host: " + uri.getHost() + ", Segments: " + uri.getPathSegments().toString());

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // LocalStorageProvider
        if (isLocalStorageDocument(uri)) {
            // The path is the id
            return DocumentsContract.getDocumentId(uri);
        }
        // ExternalStorageProvider
        else if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:com.boko.vimusic.ui.fragments.PlaylistFragment.java

/**
 * Create a new {@link AlertDialog} for easy playlist deletion
 * /* w w w. j ava 2s.c o m*/
 * @param context
 *            The {@link Context} to use
 * @param title
 *            The title of the playlist being deleted
 * @param id
 *            The ID of the playlist being deleted
 * @return A new {@link AlertDialog} used to delete playlists
 */
private final AlertDialog buildDeleteDialog() {
    return new AlertDialog.Builder(getActivity())
            .setTitle(getString(R.string.delete_dialog_title, mPlaylist.getName()))
            .setPositiveButton(R.string.context_menu_delete, new OnClickListener() {

                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    final Uri mUri = ContentUris.withAppendedId(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
                            Long.valueOf(mPlaylist.getId()));
                    getActivity().getContentResolver().delete(mUri, null, null);
                    MusicUtils.refresh(getActivity());
                }
            }).setNegativeButton(R.string.cancel, new OnClickListener() {

                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    dialog.dismiss();
                }
            }).setMessage(R.string.cannot_be_undone).create();
}

From source file:com.akop.bach.fragment.xboxlive.SentMessagesFragment.java

@Override
public void okClicked(int code, long id, String param) {
    if (code == DIALOG_CONFIRM) {
        Uri sentMessage = ContentUris.withAppendedId(SentMessages.CONTENT_URI, id);

        try {/*from  w  w w.  j  av a  2 s .  c  o m*/
            getActivity().getContentResolver().delete(sentMessage, null, null);
        } catch (Exception e) {
            mHandler.showToast(Parser.getErrorMessage(getActivity(), e));
        }
    }
}

From source file:com.andrew.apollo.ui.fragments.PlaylistFragment.java

/**
 * Create a new {@link AlertDialog} for easy playlist deletion
 * /*from   ww  w.j ava  2  s. co m*/
 * @param context The {@link Context} to use
 * @param title The title of the playlist being deleted
 * @param id The ID of the playlist being deleted
 * @return A new {@link AlertDialog} used to delete playlists
 */
private final AlertDialog buildDeleteDialog() {
    return new AlertDialog.Builder(getSherlockActivity())
            .setTitle(getString(R.string.context_menu_delete) + " " + mPlaylist.mPlaylistName)
            .setPositiveButton(R.string.context_menu_delete, new OnClickListener() {

                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    final Uri mUri = ContentUris.withAppendedId(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
                            Long.valueOf(mPlaylist.mPlaylistId));
                    getSherlockActivity().getContentResolver().delete(mUri, null, null);
                    MusicUtils.refresh();
                }
            }).setNegativeButton(R.string.cancel, new OnClickListener() {

                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    dialog.dismiss();
                }
            }).setMessage(R.string.cannot_be_undone).create();
}

From source file:com.kyakujin.android.tagnotepad.ui.NoteListFragment.java

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    AdapterView.AdapterContextMenuInfo info;
    try {//from   w w  w.j  a v  a  2  s. com
        info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    } catch (ClassCastException e) {
        Log.e(TAG, "bad AdapterContextMenuInfo", e);
        return;
    }

    Cursor c = (Cursor) mNoteListView.getAdapter().getItem(info.position);
    if (c == null) {
        return;
    }

    android.view.MenuInflater inflater = getSherlockActivity().getMenuInflater();
    inflater.inflate(R.menu.context_menu_note_list, menu);

    menu.setHeaderTitle(c.getString(NotesQuery.TITLE));

    Intent intent = new Intent(null, ContentUris.withAppendedId(Notes.CONTENT_URI, (int) info.id));
    intent.addCategory(Intent.CATEGORY_ALTERNATIVE);

    menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
            new ComponentName(getSherlockActivity(), NoteListFragment.class), null, intent, 0, null);
}

From source file:com.android.ex.chips.RecipientAlternatesAdapter.java

public RecipientEntry getRecipientEntry(int position) {
    Cursor c = getCursor();/*w ww .  j  a v a2 s .  c  o m*/
    c.moveToPosition(position);

    String photoThumbnailUri;
    int displayNameSource;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        photoThumbnailUri = c.getString(Queries.Query.PHOTO_THUMBNAIL_URI);
        displayNameSource = c.getInt(Queries.Query.DISPLAY_NAME_SOURCE);
    } else {
        long photoId = c.getLong(Queries.Query.PHOTO_ID);
        Uri photoUri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, photoId);
        photoThumbnailUri = photoUri.toString();
        displayNameSource = Query.DEFAULT_DISPLAY_NAME_SOURCE;
    }

    return RecipientEntry.constructTopLevelEntry(c.getString(Queries.Query.NAME), displayNameSource,
            c.getString(Queries.Query.DESTINATION), c.getInt(Queries.Query.DESTINATION_TYPE),
            c.getString(Queries.Query.DESTINATION_LABEL), c.getLong(Queries.Query.CONTACT_ID),
            c.getLong(Queries.Query.DATA_ID), photoThumbnailUri);
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Use custom drag and drop view
    View v = inflater.inflate(R.layout.accounts_edit_list, container, false);

    DragnDropListView lv = (DragnDropListView) v.findViewById(android.R.id.list);
    lv.setGrabberId(R.id.grabber);//from  w  ww. ja  va2 s  .c om
    // Setup the drop listener
    lv.setOnDropListener(new DropListener() {
        @Override
        public void drop(int from, int to) {
            Log.d(THIS_FILE, "Drop from " + from + " to " + to);
            int i;
            // First of all, compute what we get before move
            ArrayList<Long> orderedList = new ArrayList<Long>();
            CursorAdapter ad = (CursorAdapter) getListAdapter();
            for (i = 0; i < ad.getCount(); i++) {
                orderedList.add(ad.getItemId(i));
            }
            // Then, invert in the current list the two items ids
            Long moved = orderedList.remove(from);
            orderedList.add(to, moved);

            // Finally save that in db
            ContentResolver cr = getActivity().getContentResolver();
            for (i = 0; i < orderedList.size(); i++) {
                Uri uri = ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, orderedList.get(i));
                ContentValues cv = new ContentValues();
                cv.put(SipProfile.FIELD_PRIORITY, i);
                cr.update(uri, cv, null, null);
            }
        }
    });

    return v;
}

From source file:com.android.contacts.common.model.ContactLoaderTest.java

public void testLoadContactWithContactLookupWithIncorrectIdUri() {
    // Use lookup-style Uris that contain incorrect Contact-ID
    // (we want to ensure that still the correct contact is chosen)
    final long wrongContactId = 2;
    final long wrongRawContactId = 12;

    final String wrongLookupKey = "ab%12%@!";
    final Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, CONTACT_ID);
    final Uri wrongBaseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, wrongContactId);
    final Uri lookupUri = ContentUris
            .withAppendedId(Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, LOOKUP_KEY), CONTACT_ID);
    final Uri lookupWithWrongIdUri = ContentUris
            .withAppendedId(Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, LOOKUP_KEY), wrongContactId);
    final Uri entityUri = Uri.withAppendedPath(lookupWithWrongIdUri, Contacts.Entity.CONTENT_DIRECTORY);

    ContactQueries queries = new ContactQueries();
    mContactsProvider.expectTypeQuery(lookupWithWrongIdUri, Contacts.CONTENT_ITEM_TYPE);
    queries.fetchAllData(entityUri, CONTACT_ID, RAW_CONTACT_ID, DATA_ID, LOOKUP_KEY);

    Contact contact = assertLoadContact(lookupWithWrongIdUri);

    assertEquals(CONTACT_ID, contact.getId());
    assertEquals(RAW_CONTACT_ID, contact.getNameRawContactId());
    assertEquals(DisplayNameSources.STRUCTURED_NAME, contact.getDisplayNameSource());
    assertEquals(LOOKUP_KEY, contact.getLookupKey());
    assertEquals(lookupUri, contact.getLookupUri());
    assertEquals(1, contact.getRawContacts().size());
    assertEquals(1, contact.getStatuses().size());

    mContactsProvider.verify();/*from   ww  w .  jav a2  s  .c  o m*/
}

From source file:com.ternup.caddisfly.fragment.DetailsFragment.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();/*  w w  w.  j a v a  2 s  .c o m*/

    if (cursor.getCount() > 0) {
        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.granita.tasks.EditTaskFragment.java

@SuppressWarnings("deprecation")
@TargetApi(16)//from  w ww.j  av a  2 s. c  o  m
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ListenableScrollView rootView = mRootView = (ListenableScrollView) inflater
            .inflate(R.layout.fragment_task_edit_detail, container, false);
    mContent = (ViewGroup) rootView.findViewById(R.id.content);
    mHeader = (ViewGroup) rootView.findViewById(R.id.header);
    mColorBar = rootView.findViewById(R.id.headercolorbar);

    mRestored = savedInstanceState != null;

    if (mColorBar != null) {
        mRootView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScroll(int oldScrollY, int newScrollY) {
                int headerHeight = mTaskListBar.getMeasuredHeight();
                if (newScrollY <= headerHeight || oldScrollY <= headerHeight) {
                    updateColor((float) newScrollY / headerHeight);
                }
            }
        });
    }
    mAppForEdit = !Tasks.getContentUri(mAuthority).equals(mTaskUri) && mTaskUri != null;

    mTaskListBar = (LinearLayout) inflater.inflate(R.layout.task_list_provider_bar, mHeader);
    mListSpinner = (Spinner) mTaskListBar.findViewById(R.id.task_list_spinner);

    mTaskListAdapter = new TasksListCursorSpinnerAdapter(mAppContext);
    mListSpinner.setAdapter(mTaskListAdapter);

    mListSpinner.setOnItemSelectedListener(this);

    if (android.os.Build.VERSION.SDK_INT < 11) {
        mListSpinner.setBackgroundDrawable(null);
    }

    if (mAppForEdit) {
        if (mTaskUri != null) {
            if (savedInstanceState == null && mValues == null) {
                mValues = new ContentSet(mTaskUri);
                mValues.addOnChangeListener(this, null, false);

                mValues.update(mAppContext, CONTENT_VALUE_MAPPER);
            } else {
                if (savedInstanceState != null) {
                    mValues = savedInstanceState.getParcelable(KEY_VALUES);
                    Sources.loadModelAsync(mAppContext, mValues.getAsString(Tasks.ACCOUNT_TYPE), this);
                } else {
                    Sources.loadModelAsync(mAppContext, mValues.getAsString(Tasks.ACCOUNT_TYPE), this);
                    // ensure we're using the latest values
                    mValues.update(mAppContext, CONTENT_VALUE_MAPPER);
                }
                mListColor = TaskFieldAdapters.LIST_COLOR.get(mValues);
                // update the color of the action bar as soon as possible
                updateColor(0);
                setListUri(ContentUris.withAppendedId(TaskLists.getContentUri(mAuthority),
                        mValues.getAsLong(Tasks.LIST_ID)), null);
            }
            // disable spinner
            mListSpinner.setEnabled(false);
            // hide spinner background
            if (android.os.Build.VERSION.SDK_INT >= 16) {
                mListSpinner.setBackground(null);
            }
        }
    } else {
        if (savedInstanceState == null) {
            // create empty ContentSet if there was no ContentSet supplied
            if (mValues == null) {
                mValues = new ContentSet(Tasks.getContentUri(mAuthority));
                // ensure we start with the current time zone
                TaskFieldAdapters.TIMEZONE.set(mValues, TimeZone.getDefault());
            } else {
                // check id the provided content set contains a list and update the selected list if so
                Long listId = mValues.getAsLong(Tasks.LIST_ID);
                if (listId != null) {
                    mSelectedList = listId;
                }
            }

            if (mLastAccountType != null) {
                Sources.loadModelAsync(mAppContext, mLastAccountType, this);
            }
        } else {
            mValues = savedInstanceState.getParcelable(KEY_VALUES);
            Sources.loadModelAsync(mAppContext, mLastAccountType, this);
        }
        setListUri(TaskLists.getContentUri(mAuthority), LIST_LOADER_VISIBLE_LISTS_FILTER);
    }

    return rootView;
}