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.jefftharris.passwdsafe.sync.MainActivity.java

/** Update the UI when the ownCloud account is changed */
private void updateOwncloudAccount(Cursor cursor) {
    boolean haveCursor = (cursor != null);
    GuiUtils.setVisible(findViewById(R.id.owncloud_container), haveCursor);
    GuiUtils.setVisible(findViewById(R.id.owncloud_separator), haveCursor);
    if (haveCursor) {
        long id = cursor.getLong(PasswdSafeContract.Providers.PROJECTION_IDX_ID);
        String acct = PasswdSafeContract.Providers.getDisplayName(cursor);
        itsOwncloudSyncFreq = cursor.getInt(PasswdSafeContract.Providers.PROJECTION_IDX_SYNC_FREQ);
        itsOwncloudUri = ContentUris.withAppendedId(PasswdSafeContract.Providers.CONTENT_URI, id);

        OwncloudProvider provider = getOwncloudProvider();
        boolean authorized = provider.isAccountAuthorized();

        TextView acctView = (TextView) findViewById(R.id.owncloud_acct);
        assert acctView != null;
        acctView.setText(acct);//from  w w w .  ja  v a  2 s  . c o  m

        GuiUtils.setVisible(findViewById(R.id.owncloud_auth_required), !authorized);
    } else {
        itsOwncloudUri = null;
    }
}

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

private void loadDirectoryMetaData(Contact result) {
    long directoryId = result.getDirectoryId();

    Cursor cursor = getContext().getContentResolver().query(
            ContentUris.withAppendedId(Directory.CONTENT_URI, directoryId), DirectoryQuery.COLUMNS, null, null,
            null);//ww w .  j  a  v  a2 s .  c om
    if (cursor == null) {
        return;
    }
    try {
        if (cursor.moveToFirst()) {
            final String displayName = cursor.getString(DirectoryQuery.DISPLAY_NAME);
            final String packageName = cursor.getString(DirectoryQuery.PACKAGE_NAME);
            final int typeResourceId = cursor.getInt(DirectoryQuery.TYPE_RESOURCE_ID);
            final String accountType = cursor.getString(DirectoryQuery.ACCOUNT_TYPE);
            final String accountName = cursor.getString(DirectoryQuery.ACCOUNT_NAME);
            final int exportSupport = cursor.getInt(DirectoryQuery.EXPORT_SUPPORT);
            String directoryType = null;
            if (!TextUtils.isEmpty(packageName)) {
                PackageManager pm = getContext().getPackageManager();
                try {
                    Resources resources = pm.getResourcesForApplication(packageName);
                    directoryType = resources.getString(typeResourceId);
                } catch (NameNotFoundException e) {
                    Log.w(TAG, "Contact directory resource not found: " + packageName + "." + typeResourceId);
                }
            }

            result.setDirectoryMetaData(displayName, directoryType, accountType, accountName, exportSupport);
        }
    } finally {
        cursor.close();
    }
}

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

private Uri insertSource(@NonNull final Uri uri, final ContentValues initialValues) {
    Context context = getContext();
    if (context == null) {
        return null;
    }/*  w  w w.  j a v  a2 s  . c o  m*/
    if (!initialValues.containsKey(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME)
            || TextUtils.isEmpty(initialValues.getAsString(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME))) {
        throw new IllegalArgumentException("Initial values must contain component name " + initialValues);
    }
    ComponentName componentName = ComponentName
            .unflattenFromString(initialValues.getAsString(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME));
    if (componentName == null) {
        throw new IllegalArgumentException("Invalid component name: "
                + initialValues.getAsString(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME));
    }
    ApplicationInfo info;
    try {
        // Ensure the service is valid and extract the application info
        info = context.getPackageManager().getServiceInfo(componentName, 0).applicationInfo;
    } catch (PackageManager.NameNotFoundException e) {
        throw new IllegalArgumentException("Invalid component name "
                + initialValues.getAsString(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME), e);
    }
    // Make sure they are using the short string format
    initialValues.put(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME, componentName.flattenToShortString());

    // Only Muzei can set the IS_SELECTED field
    if (initialValues.containsKey(MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED)) {
        if (!context.getPackageName().equals(getCallingPackage())) {
            Log.w(TAG, "Only Muzei can set the " + MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED
                    + " column. Ignoring the value in " + initialValues);
            initialValues.remove(MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED);
        }
    }

    // Disable network access callbacks if we're running on an API 24 device and the source app
    // targets API 24. This is to be consistent with the Behavior Changes in Android N
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
            && initialValues.containsKey(MuzeiContract.Sources.COLUMN_NAME_WANTS_NETWORK_AVAILABLE)
            && initialValues.getAsBoolean(MuzeiContract.Sources.COLUMN_NAME_WANTS_NETWORK_AVAILABLE)) {
        if (info.targetSdkVersion >= Build.VERSION_CODES.N) {
            Log.w(TAG,
                    "Sources targeting API 24 cannot receive network access callbacks. Changing "
                            + componentName + " to false for "
                            + MuzeiContract.Sources.COLUMN_NAME_WANTS_NETWORK_AVAILABLE);
            initialValues.put(MuzeiContract.Sources.COLUMN_NAME_WANTS_NETWORK_AVAILABLE, false);
        }
    }
    final SQLiteDatabase db = databaseHelper.getWritableDatabase();
    final long rowId = db.insert(MuzeiContract.Sources.TABLE_NAME,
            MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME, initialValues);
    // If the insert succeeded, the row ID exists.
    if (rowId > 0) {
        // Creates a URI with the source ID pattern and the new row ID appended to it.
        final Uri sourceUri = ContentUris.withAppendedId(MuzeiContract.Sources.CONTENT_URI, rowId);
        notifyChange(sourceUri);
        return sourceUri;
    }
    // If the insert didn't succeed, then the rowID is <= 0
    throw new SQLException("Failed to insert row into " + uri);
}

From source file:ngo.music.soundcloudplayer.controller.SongController.java

public void deleteSong(Song song) {
    MusicPlayerService.getInstance().removeFromQueue(song, true);
    if (song instanceof OfflineSong) {
        Uri deleteUri = ContentUris.withAppendedId(Media.EXTERNAL_CONTENT_URI, Integer.valueOf(song.getId()));
        MusicPlayerService.getInstance().getContentResolver().delete(deleteUri, null, null);
        File file;// w  ww.  j a  v  a  2s  . c o  m
        try {
            file = new File(song.getLink());
            if (file.isFile()) {
                if (file.exists()) {
                    file.delete();

                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    UIController.getInstance().updateUiWhenDataChanged(OFFLINE_SONG_CHANGED);

}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MusicUtils.java

private static Bitmap getArtworkQuick(Context context, long album_id, int w, int h) {
    // NOTE: There is in fact a 1 pixel border on the right side in the ImageView
    // used to display this drawable. Take it into account now, so we don't have to
    // scale later.
    w -= 1;// w w w . j  a v a  2  s  .  c  o m
    ContentResolver res = context.getContentResolver();
    Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
    if (uri != null) {
        ParcelFileDescriptor fd = null;
        try {
            fd = res.openFileDescriptor(uri, "r");
            int sampleSize = 1;

            // Compute the closest power-of-two scale factor
            // and pass that to sBitmapOptionsCache.inSampleSize, which will
            // result in faster decoding and better quality
            sBitmapOptionsCache.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache);
            int nextWidth = sBitmapOptionsCache.outWidth >> 1;
            int nextHeight = sBitmapOptionsCache.outHeight >> 1;
            while (nextWidth > w && nextHeight > h) {
                sampleSize <<= 1;
                nextWidth >>= 1;
                nextHeight >>= 1;
            }

            sBitmapOptionsCache.inSampleSize = sampleSize;
            sBitmapOptionsCache.inJustDecodeBounds = false;
            Bitmap b = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache);

            if (b != null) {
                // finally rescale to exactly the size we need
                if (sBitmapOptionsCache.outWidth != w || sBitmapOptionsCache.outHeight != h) {
                    Bitmap tmp = Bitmap.createScaledBitmap(b, w, h, true);
                    // Bitmap.createScaledBitmap() can return the same bitmap
                    if (tmp != b)
                        b.recycle();
                    b = tmp;
                }
            }

            return b;
        } catch (FileNotFoundException e) {
        } finally {
            try {
                if (fd != null)
                    fd.close();
            } catch (IOException e) {
            }
        }
    }
    return null;
}

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

/**
 * Save updated photo for the specified raw-contact.
 * @return true for success, false for failure
 *//*from   w  w  w.ja v  a 2  s  .  c  om*/
private boolean saveUpdatedPhoto(long rawContactId, Uri photoUri, int saveMode) {
    final Uri outputUri = Uri.withAppendedPath(
            ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId),
            RawContacts.DisplayPhoto.CONTENT_DIRECTORY);

    return ContactPhotoUtils.savePhotoFromUriToUri(this, photoUri, outputUri, (saveMode == 0));
}

From source file:com.akop.bach.parser.PsnUsParser.java

protected void parseFriends(PsnAccount account) throws ParserException, IOException {
    synchronized (PsnUsParser.class) {
        String url = String.format(URL_FRIENDS, Math.random());
        HttpUriRequest request = new HttpGet(url);

        request.addHeader("Referer", "http://us.playstation.com/myfriends/");
        request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        String page = getResponse(request, null);

        ContentResolver cr = mContext.getContentResolver();
        final long accountId = account.getId();
        ContentValues cv;//from  w  w  w.  ja v a  2 s  .c om
        List<ContentValues> newCvs = new ArrayList<ContentValues>(100);

        int rowsInserted = 0;
        int rowsUpdated = 0;
        int rowsDeleted = 0;

        long updated = System.currentTimeMillis();
        long started = updated;
        Matcher gameMatcher = PATTERN_FRIENDS.matcher(page);

        while (gameMatcher.find()) {
            String friendGt = htmlDecode(gameMatcher.group(1));
            GamerProfileInfo gpi;

            try {
                gpi = parseGamerProfile(account, friendGt);
            } catch (IOException e) {
                if (App.getConfig().logToConsole())
                    App.logv("Friend " + friendGt + " threw an IOException");

                // Update the DeleteMarker, so that the GT is not removed

                cv = new ContentValues(15);
                cv.put(Friends.DELETE_MARKER, updated);

                cr.update(Friends.CONTENT_URI, cv,
                        Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?",
                        new String[] { friendGt });

                continue;
            } catch (Exception e) {
                // The rest of the exceptions assume problems with Friend
                // and potentially remove him/her

                if (App.getConfig().logToConsole()) {
                    App.logv("Friend " + friendGt + " threw an Exception");
                    e.printStackTrace();
                }

                continue;
            }

            Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION,
                    Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?",
                    new String[] { friendGt }, null);

            long friendId = -1;

            if (c != null) {
                try {
                    if (c.moveToFirst())
                        friendId = c.getLong(0);
                } finally {
                    c.close();
                }
            }

            cv = new ContentValues(15);

            cv.put(Friends.ONLINE_ID, gpi.OnlineId);
            cv.put(Friends.ICON_URL, gpi.AvatarUrl);
            cv.put(Friends.LEVEL, gpi.Level);
            cv.put(Friends.PROGRESS, gpi.Progress);
            cv.put(Friends.ONLINE_STATUS, gpi.OnlineStatus);
            cv.put(Friends.TROPHIES_PLATINUM, gpi.PlatinumTrophies);
            cv.put(Friends.TROPHIES_GOLD, gpi.GoldTrophies);
            cv.put(Friends.TROPHIES_SILVER, gpi.SilverTrophies);
            cv.put(Friends.TROPHIES_BRONZE, gpi.BronzeTrophies);
            cv.put(Friends.PLAYING, gpi.Playing);
            cv.put(Friends.DELETE_MARKER, updated);
            cv.put(Friends.LAST_UPDATED, updated);

            if (friendId < 0) {
                // New
                cv.put(Friends.ACCOUNT_ID, accountId);

                newCvs.add(cv);
            } else {
                cr.update(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), cv, null, null);

                rowsUpdated++;
            }
        }

        // Remove friends
        rowsDeleted = cr.delete(Friends.CONTENT_URI,
                Friends.ACCOUNT_ID + "=" + accountId + " AND " + Friends.DELETE_MARKER + "!=" + updated, null);

        if (newCvs.size() > 0) {
            ContentValues[] cvs = new ContentValues[newCvs.size()];
            newCvs.toArray(cvs);

            rowsInserted = cr.bulkInsert(Friends.CONTENT_URI, cvs);
        }

        account.refresh(Preferences.get(mContext));
        account.setLastFriendUpdate(System.currentTimeMillis());
        account.save(Preferences.get(mContext));

        cr.notifyChange(Friends.CONTENT_URI, null);

        if (App.getConfig().logToConsole())
            started = displayTimeTaken("Friend page processing [I:" + rowsInserted + ";U:" + rowsUpdated + ";D:"
                    + rowsDeleted + "]", started);
    }
}

From source file:org.gege.caldavsyncadapter.caldav.entities.CalendarEvent.java

/**
 * searches for an android event/*from   w ww. j a  va  2s . co m*/
 * @param androidCalendar
 * @return the android event
 * @throws RemoteException
 */
public AndroidEvent getAndroidEvent(DavCalendar androidCalendar) throws RemoteException {
    boolean Error = false;
    Uri uriEvents = Events.CONTENT_URI;
    Uri uriAttendee = Attendees.CONTENT_URI;
    Uri uriReminder = Reminders.CONTENT_URI;
    AndroidEvent androidEvent = null;

    String selection = "(" + Events._SYNC_ID + " = ?)";
    String[] selectionArgs = new String[] { this.getUri().toString() };
    Cursor curEvent = this.mProvider.query(uriEvents, null, selection, selectionArgs, null);

    Cursor curAttendee = null;
    Cursor curReminder = null;

    if (curEvent == null) {
        Error = true;
    }
    if (!Error) {
        if (curEvent.getCount() == 0) {
            Error = true;
        }
    }
    if (!Error) {
        curEvent.moveToNext();

        long EventID = curEvent.getLong(curEvent.getColumnIndex(Events._ID));
        Uri returnedUri = ContentUris.withAppendedId(uriEvents, EventID);

        androidEvent = new AndroidEvent(this.mAccount, this.mProvider, returnedUri,
                androidCalendar.getAndroidCalendarUri());
        androidEvent.readContentValues(curEvent);

        selection = "(" + Attendees.EVENT_ID + " = ?)";
        selectionArgs = new String[] { String.valueOf(EventID) };
        curAttendee = this.mProvider.query(uriAttendee, null, selection, selectionArgs, null);
        selection = "(" + Reminders.EVENT_ID + " = ?)";
        selectionArgs = new String[] { String.valueOf(EventID) };
        curReminder = this.mProvider.query(uriReminder, null, selection, selectionArgs, null);
        androidEvent.readAttendees(curAttendee);
        androidEvent.readReminder(curReminder);
        curAttendee.close();
        curReminder.close();
    }
    curEvent.close();

    return androidEvent;
}

From source file:com.example.mydemos.view.RingtonePickerActivity.java

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
    Log.e("lys", "onItemClick position ==" + position + "id" + id);
    if (id == -1) {
        if (mHasSilentItem) {

            if ((mHasDefaultItem && (position == 1)) || !mHasDefaultItem) {
                Log.e("lys", "onItemClick silentItemChecked == true");
                //toneCur.moveToPosition(position);
                mSelectedId = SILENT_ID;
                mSelectedUri = null;/*from ww  w .  j a  v a 2  s. com*/
                silentItemChecked = true;
                defaultItemChecked = false;
                stopMediaPlayer();
                listView.invalidateViews();
                return;
            } else if (mHasDefaultItem && (position == 0)) {
                Log.e("lys", "onItemClick defaultItemChecked == true");
                //toneCur.moveToPosition(position);
                mSelectedId = DEFAULT_ID;
                mSelectedUri = mUriForDefaultItem;
                defaultItemChecked = true;
                silentItemChecked = false;
            }
        } else {
            if (mHasDefaultItem) {
                Log.e("lys", "onItemClick defaultItemChecked == true");
                //toneCur.moveToPosition(position);
                mSelectedId = DEFAULT_ID;
                mSelectedUri = mUriForDefaultItem;
                defaultItemChecked = true;
                silentItemChecked = false;
            }
        }

    } else {
        if (mHasSilentItem) {
            silentItemChecked = false;
            position--;
        }

        if (mHasDefaultItem) {
            defaultItemChecked = false;
            position--;
        }
    }
    if (id != -1) {
        toneCur.moveToPosition(position);
        Log.e("lys", "onItemClick position == " + position + "id ==" + id);
        long newId = toneCur.getLong(toneCur.getColumnIndex(MediaStore.Audio.Media._ID));
        mSelectedId = newId;
        Log.e("lys", " onItemClick mSelectedId==" + mSelectedId);

        //wuqingliang modify begin20130307
        if (tabName == SYSTEM_TONE) {
            BaseUri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
            Log.e("lys", "BaseUri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;111111");
        } else {
            BaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            Log.e("lys", "BaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;1111111");
        }
        //wuqingliang modify end
        mSelectedUri = ContentUris.withAppendedId(BaseUri, newId);
    }
    listView.invalidateViews();
    audioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    stopMediaPlayer();
    mMediaPlayer = new MediaPlayer();
    try {
        if (toneType == ALARM_TYPE)
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        else
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
        mMediaPlayer.setDataSource(RingtonePickerActivity.this, mSelectedUri);
        mMediaPlayer.prepare();
        mMediaPlayer.start();

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.fabernovel.alertevoirie.ReportDetailsActivity.java

private void setCategory(long l) {
    String subCategories = EMPTY_STRING, category = EMPTY_STRING;
    long catId = l;
    //Log.d(Constants.PROJECT_TAG, "Cat id = " + catId);
    currentIncident.categoryId = catId;/*from   ww  w .  j  a v a2 s.  co  m*/

    do {
        Cursor c = getContentResolver().query(ContentUris.withAppendedId(Category.CONTENT_URI, catId),
                new String[] { Category.PARENT, Category.NAME }, null, null, null);

        if (c.moveToFirst()) {
            catId = c.getInt(c.getColumnIndex(Category.PARENT));
            if (catId != 0) {
                subCategories = c.getString(c.getColumnIndex(Category.NAME))
                        + (subCategories.length() > 0 ? ", " + subCategories : EMPTY_STRING);
            } else {
                category = c.getString(c.getColumnIndex(Category.NAME));
            }
        }
        c.close();
    } while (catId > 0);

    ((TextView) findViewById(R.id.TextView_sub_categories)).setText(subCategories);
    ((TextView) findViewById(R.id.TextView_main_category)).setText(category);

}