Example usage for android.content ContentUris parseId

List of usage examples for android.content ContentUris parseId

Introduction

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

Prototype

public static long parseId(Uri contentUri) 

Source Link

Document

Converts the last path segment to a long.

Usage

From source file:ca.marcmeszaros.papyrus.browser.BooksBrowser.java

/**
 * Executes the query to loan out the book
 *///  w w  w  .jav a  2 s . c o  m
private void loanBook(int mYear, int mMonth, int mDay) {
    // set the due date
    Calendar c = Calendar.getInstance();
    c.set(mYear, mMonth, mDay);

    // gets the uri path to the user selected
    Uri user = loanData.getData();

    // gets the user id
    String id = user.getLastPathSegment();

    // prepare the query
    ContentValues values = new ContentValues();
    values.put(PapyrusContentProvider.Loans.FIELD_BOOK_ID, selectedBookID);
    values.put(PapyrusContentProvider.Loans.FIELD_CONTACT_ID, id);
    values.put(PapyrusContentProvider.Loans.FIELD_LEND_DATE, System.currentTimeMillis());
    values.put(PapyrusContentProvider.Loans.FIELD_DUE_DATE, c.getTimeInMillis());

    // insert the entry in the database, and get the new loan id
    Uri newLoan = resolver.insert(PapyrusContentProvider.Loans.CONTENT_URI, values);
    int loanID = (int) ContentUris.parseId(newLoan);

    // Book book = new Book(isbn10, title, author);
    Loan loan = new Loan(loanID, values.getAsInteger(PapyrusContentProvider.Loans.FIELD_BOOK_ID),
            values.getAsInteger(PapyrusContentProvider.Loans.FIELD_CONTACT_ID),
            values.getAsLong(PapyrusContentProvider.Loans.FIELD_LEND_DATE),
            values.getAsLong(PapyrusContentProvider.Loans.FIELD_DUE_DATE));

    // get an alarm manager
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    // create the intent for the alarm
    Intent intent = new Intent(this, AlarmReceiver.class);

    // put the loan object into the alarm receiver
    intent.putExtra("loan", loan);

    // create the pendingIntent to run when the alarm goes off and be handled by a receiver
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    // set the repeating alarm
    am.set(AlarmManager.RTC, c.getTimeInMillis(), pendingIntent);

    Toast.makeText(this, getString(R.string.BooksBrowser_toast_loanSuccessful), Toast.LENGTH_LONG).show();
}

From source file:org.dmfs.tasks.notification.NotificationUpdaterService.java

@SuppressLint("InlinedApi")
public void resendPinNotification(Uri taskUri) {
    if (taskUri == null) {
        return;//from  w w w.jav  a  2 s  .c  o m
    }
    long taskId = ContentUris.parseId(taskUri);
    if (taskId < 0) {
        return;
    }
    Integer notificationId = Long.valueOf(taskId).intValue();
    mBuilder.setDefaults(Notification.DEFAULT_ALL);
    mBuilder.setOngoing(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mBuilder.setPriority(Notification.PRIORITY_HIGH);
    }

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(notificationId, mBuilder.build());
}

From source file:com.example.tony.popularmovie.DetailActivityFragment.java

private void insertFavorite() {
    ContentValues contentValues = new ContentValues();

    contentValues.put(MovieContract.FavoriteEntry.COLUMN_MOVIE_ID, sMovieId);
    contentValues.put(MovieContract.FavoriteEntry.COLUMN_MOVIE_TITLE, sMovieTitle);
    contentValues.put(MovieContract.FavoriteEntry.COLUMN_RELEASE_DATE, sReleaseDate);
    contentValues.put(MovieContract.FavoriteEntry.COLUMN_MOVIE_POSTER, sMoviePoster);
    contentValues.put(MovieContract.FavoriteEntry.COLUMN_VOTE_AVERAGE, sVoteAverage);
    contentValues.put(MovieContract.FavoriteEntry.COLUMN_PLOT_SYNOPSYS, sPlotSynopsis);
    contentValues.put(MovieContract.FavoriteEntry.COLUMN_POPULARITY, sPopularity);

    Uri uri = getActivity().getContentResolver().insert(MovieContract.FavoriteEntry.CONTENT_URI, contentValues);
    long rowId = ContentUris.parseId(uri);

    if (rowId == -1)
        Log.d("Detail", "Favorite insert fail");
}

From source file:com.renjunzheng.vendingmachine.MyGcmListenerService.java

private void loginFeedback(String login_status_code, Bundle data) {
    SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
            .edit();/*w  ww. j  ava 2  s.  com*/
    editor.putBoolean("login_checked", true);
    int returnCode = Integer.parseInt(login_status_code);
    editor.putInt("login_status_code", returnCode);
    editor.apply();

    if (returnCode == 200) {
        ContentValues newValues = new ContentValues();
        newValues.put(DataContract.UserEntry.COLUMN_DISPLAY_NAME, data.getString("real_name"));
        newValues.put(DataContract.UserEntry.COLUMN_MONEY_LEFT, data.getString("balance"));

        String selection = DataContract.UserEntry.COLUMN_EMAIL + " =?";
        String[] selectionArgs = { data.getString("email") };
        int rowUpdated = getContentResolver().update(DataContract.UserEntry.CONTENT_URI, newValues, selection,
                selectionArgs);
        if (rowUpdated == 0) {
            newValues.put(DataContract.UserEntry.COLUMN_EMAIL, data.getString("email"));
            Uri returnedUri = getContentResolver().insert(DataContract.UserEntry.CONTENT_URI, newValues);
            Log.i(TAG, "inserted row num " + ContentUris.parseId(returnedUri));
        } else {
            Log.i(TAG, "updated row num " + Integer.toString(rowUpdated));
        }

    }
}

From source file:com.shinymayhem.radiopresets.ActivityMain.java

@Override
public void onDialogPositiveClick(View view) {
    // User touched the dialog's positive button
    if (LOCAL_LOGD)
        log("Add station confirmed", "d");
    EditText titleView = (EditText) view.findViewById(R.id.station_title);
    EditText urlView = (EditText) view.findViewById(R.id.station_url);

    //int preset = 1; 
    String title = titleView.getText().toString().trim();
    String url = urlView.getText().toString().trim();
    boolean valid = ServiceRadioPlayer.validateUrl(url);
    if (valid) {/*from   w ww.  j  a  va  2  s  .  c o  m*/
        ContentValues values = new ContentValues();
        //values.put(DbContractRadio.EntryStation.COLUMN_NAME_PRESET_NUMBER, preset);
        values.put(DbContractRadio.EntryStation.COLUMN_NAME_TITLE, title);
        values.put(DbContractRadio.EntryStation.COLUMN_NAME_URL, url);
        Uri uri = getContentResolver().insert(ContentProviderRadio.CONTENT_URI_STATIONS, values);
        int id = (int) ContentUris.parseId(uri);
        if (id == -1) {
            throw new SQLiteException("Insert failed");
        }
        if (LOCAL_LOGV)
            log("uri of addition:" + uri, "v");
        this.updateDetails();
    } else {
        //FIXME code duplication in FragmentStations
        if (LOCAL_LOGV)
            log("URL " + url + " not valid", "v");
        LayoutInflater inflater = LayoutInflater.from(this);
        final View editView = inflater.inflate(R.layout.dialog_station_details, null);
        titleView = ((EditText) editView.findViewById(R.id.station_title));
        titleView.setText(title);
        urlView = ((EditText) editView.findViewById(R.id.station_url));
        urlView.setText(url);
        urlView.requestFocus();
        AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
        builder.setView(editView);
        builder.setPositiveButton(R.string.edit_station, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                onDialogPositiveClick(editView);
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                onDialogNegativeClick();

            }
        });
        builder.setTitle("URL appears invalid. Try again");
        builder.show();
        //TODO
    }
}

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

private void createContactShortcutIntent(Uri contactUri, String contentType, String displayName,
        String lookupKey, byte[] bitmapData) {
    Intent intent = null;//  w  w  w.  java2 s.  co  m
    if (TextUtils.isEmpty(displayName)) {
        displayName = mContext.getResources().getString(R.string.missing_name);
    }
    if (BuildCompat.isAtLeastO()) {
        final long contactId = ContentUris.parseId(contactUri);
        final ShortcutManager sm = (ShortcutManager) mContext.getSystemService(Context.SHORTCUT_SERVICE);
        final DynamicShortcuts dynamicShortcuts = new DynamicShortcuts(mContext);
        final ShortcutInfo shortcutInfo = dynamicShortcuts.getQuickContactShortcutInfo(contactId, lookupKey,
                displayName);
        if (shortcutInfo != null) {
            intent = sm.createShortcutResultIntent(shortcutInfo);
        }
    }
    final Drawable drawable = getPhotoDrawable(bitmapData, displayName, lookupKey);

    final Intent shortcutIntent = ImplicitIntentsUtil.getIntentForQuickContactLauncherShortcut(mContext,
            contactUri);

    intent = intent == null ? new Intent() : intent;

    final Bitmap icon = generateQuickContactIcon(drawable);
    if (BuildCompat.isAtLeastO()) {
        final IconCompat compatIcon = IconCompat.createWithAdaptiveBitmap(icon);
        compatIcon.addToShortcutIntent(intent, null, mContext);
    } else {
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon);
    }
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, displayName);

    mListener.onShortcutIntentCreated(contactUri, intent);
}

From source file:mobisocial.socialkit.musubi.Musubi.java

public DbObj objForUri(Uri objUri) {
    try {/*from   www.  j a  v a2 s  .c o m*/
        return objForId(ContentUris.parseId(objUri));
    } catch (Exception e) {
        if (DBG)
            Log.e(TAG, "Bad uri " + objUri);
        return null;
    }
}

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

@Override
public int delete(Uri uri, String where, String[] whereArgs) {

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    String finalWhere;//from  w w  w.  j  av  a2s.  co  m
    int count = 0;
    int matched = URI_MATCHER.match(uri);
    Uri regUri = uri;

    ArrayList<Long> oldRegistrationsAccounts = null;

    switch (matched) {
    case ACCOUNTS:
        count = db.delete(SipProfile.ACCOUNTS_TABLE_NAME, where, whereArgs);
        break;
    case ACCOUNTS_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipProfile.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipProfile.ACCOUNTS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case CALLLOGS:
        count = db.delete(SipManager.CALLLOGS_TABLE_NAME, where, whereArgs);
        break;
    case CALLLOGS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(CallLog.Calls._ID + " = " + ContentUris.parseId(uri),
                where);
        count = db.delete(SipManager.CALLLOGS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case FILTERS:
        count = db.delete(SipManager.FILTERS_TABLE_NAME, where, whereArgs);
        break;
    case FILTERS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(Filter._ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipManager.FILTERS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case MESSAGES:
        count = db.delete(SipMessage.MESSAGES_TABLE_NAME, where, whereArgs);
        break;
    case MESSAGES_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipMessage.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipMessage.MESSAGES_TABLE_NAME, finalWhere, whereArgs);
        break;
    case THREADS_ID:
        String from = uri.getLastPathSegment();
        if (!TextUtils.isEmpty(from)) {
            count = db.delete(SipMessage.MESSAGES_TABLE_NAME, MESSAGES_THREAD_SELECTION,
                    new String[] { from, from });
        } else {
            count = 0;
        }
        regUri = SipMessage.MESSAGE_URI;
        break;
    case ACCOUNTS_STATUS:
        oldRegistrationsAccounts = new ArrayList<Long>();
        synchronized (profilesStatus) {
            for (Long accId : profilesStatus.keySet()) {
                oldRegistrationsAccounts.add(accId);
            }
            profilesStatus.clear();
        }
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            profilesStatus.remove(id);
        }
        break;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    getContext().getContentResolver().notifyChange(regUri, null);

    if (matched == ACCOUNTS_ID || matched == ACCOUNTS_STATUS_ID) {
        long rowId = ContentUris.parseId(uri);
        if (rowId >= 0) {
            if (matched == ACCOUNTS_ID) {
                broadcastAccountChange(rowId);
            } else if (matched == ACCOUNTS_STATUS_ID) {
                broadcastRegistrationChange(rowId);
            }
        }
    }
    if (matched == FILTERS || matched == FILTERS_ID) {
        Filter.resetCache();
    }
    if (matched == ACCOUNTS_STATUS && oldRegistrationsAccounts != null) {
        for (Long accId : oldRegistrationsAccounts) {
            if (accId != null) {
                broadcastRegistrationChange(accId);
            }
        }
    }

    return count;
}

From source file:cz.maresmar.sfm.view.credential.LoginDetailActivity.java

private void saveAndValidateCredential() {
    CredentialDetailFragment credentialDetailFragment = (CredentialDetailFragment) mSectionsPagerAdapter
            .instantiateItem(mViewPager, CREDENTIAL_TAB);
    mCredentialFormDestroyer = credentialDetailFragment;
    PortalDetailFragment portalDetailFragment = (PortalDetailFragment) mSectionsPagerAdapter
            .instantiateItem(mViewPager, PORTAL_TAB);
    mPortalFormDestroyer = portalDetailFragment;

    // Propagates portal ID change in portal fragment to credentials fragment
    Uri newPortalUri = portalDetailFragment.getDataUri();
    if (mPortalUri != null && !mPortalUri.equals(newPortalUri)) {
        mPortalUri = newPortalUri;//  ww w .  ja  v a 2  s . com
        mSaveAll = false;
    }

    // (Save credentials and exit) or (only show them)
    if (mSaveAll && mPortalUri != null) {
        // Check credentials
        if (credentialDetailFragment.hasValidData()) {
            // Save credentials
            mCredentialUri = credentialDetailFragment.saveData();
            mValidatedCredentialId = ContentUris.parseId(mCredentialUri);

            // Starts "credentials test"
            SyncHandler.startFullSync(this);
        } else {
            // Show credential tab
            mViewPager.setCurrentItem(CREDENTIAL_TAB);

            // Cancel work in process UI
            mSwipeRefreshLayout.setRefreshing(false);
            if (mActiveToast != null) {
                mActiveToast.cancel();
            }
        }
    } else {
        mPortalUri = portalDetailFragment.getDataUri();

        // Show credential tab
        credentialDetailFragment.reset(mUserUri, mPortalUri);
        mViewPager.setCurrentItem(CREDENTIAL_TAB);

        // Cancel work in process UI
        mSwipeRefreshLayout.setRefreshing(false);
        if (mActiveToast != null) {
            mActiveToast.cancel();
        }
    }
}

From source file:org.kontalk.ui.ConversationsActivity.java

private void askGroupSubject(final Set<String> usersList, final String groupJid) {
    new MaterialDialog.Builder(this).title(R.string.title_group_subject).positiveText(android.R.string.ok)
            .negativeText(android.R.string.cancel).input(null, null, true, new MaterialDialog.InputCallback() {
                @Override/*from ww w  .  j  ava  2  s .c  o m*/
                public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                    String title = !TextUtils.isEmpty(input) ? input.toString() : null;
                    Context ctx = ConversationsActivity.this;

                    String[] users = usersList.toArray(new String[usersList.size()]);
                    long groupThreadId = Conversation.initGroupChat(ctx, groupJid, title, users, "");

                    // store create group command to outbox
                    // NOTE: group chats can currently only be created with chat encryption enabled
                    boolean encrypted = Preferences.getEncryptionEnabled(ctx);
                    String msgId = MessageCenterService.messageId();
                    Uri cmdMsg = KontalkGroupCommands.createGroup(ctx, groupThreadId, groupJid, users, msgId,
                            encrypted);
                    // TODO check for null

                    // send create group command now
                    MessageCenterService.createGroup(ConversationsActivity.this, groupJid, title, users,
                            encrypted, ContentUris.parseId(cmdMsg), msgId);

                    // load the new conversation
                    openConversation(Threads.getUri(groupJid), true);
                }
            }).inputRange(0, MyMessages.Groups.GROUP_SUBJECT_MAX_LENGTH).show();
}