Example usage for android.provider BaseColumns _ID

List of usage examples for android.provider BaseColumns _ID

Introduction

In this page you can find the example usage for android.provider BaseColumns _ID.

Prototype

String _ID

To view the source code for android.provider BaseColumns _ID.

Click Source Link

Document

The unique ID for a row.

Usage

From source file:org.spontaneous.trackservice.RemoteService.java

public TrackModel readTrackAndSegmentsById(Long trackId) {

    TrackModel trackModel = null;//from w w w .  ja  v  a  2  s . co m

    if (trackId != null) {
        String[] mTrackColumns = { Tracks._ID, Tracks.NAME, Tracks.TOTAL_DISTANCE, Tracks.TOTAL_DURATION,
                Tracks.USER_ID, Tracks.CREATION_TIME };

        // Read track
        Uri trackReadUri = Uri.withAppendedPath(Tracks.CONTENT_URI, String.valueOf(trackId));
        Cursor mCursor = getContentResolver().query(trackReadUri, mTrackColumns, null, null,
                Tracks.CREATION_TIME);
        if (mCursor != null && mCursor.moveToNext()) {

            trackModel = new TrackModel(Long.valueOf(mCursor.getString(mCursor.getColumnIndex(Tracks._ID))),
                    mCursor.getString(mCursor.getColumnIndex(Tracks.NAME)),
                    mCursor.getFloat(mCursor.getColumnIndex(Tracks.TOTAL_DISTANCE)),
                    mCursor.getLong(mCursor.getColumnIndex(Tracks.TOTAL_DURATION)),
                    mCursor.getLong(mCursor.getColumnIndex(Tracks.CREATION_TIME)),
                    Integer.valueOf(mCursor.getColumnIndex(Tracks.USER_ID)));

            // Read Segments and wayPoints
            String[] mSegmentsColumns = { BaseColumns._ID, SegmentsColumns.TRACK, SegmentsColumns.START_TIME,
                    SegmentsColumns.END_TIME };
            Uri segmentReadUri = Uri.withAppendedPath(Tracks.CONTENT_URI,
                    String.valueOf(trackId) + "/segments/");
            Cursor mSegmentsCursor = getContentResolver().query(segmentReadUri, mSegmentsColumns, null, null,
                    Segments._ID);

            if (mSegmentsCursor != null) {
                SegmentModel segmentModel = null;
                while (mSegmentsCursor.moveToNext()) {
                    segmentModel = new SegmentModel();
                    segmentModel.setId(Long
                            .valueOf(mSegmentsCursor.getString(mSegmentsCursor.getColumnIndex(Segments._ID))));
                    segmentModel.setTrackId(Long.valueOf(
                            mSegmentsCursor.getString(mSegmentsCursor.getColumnIndex(Segments.TRACK))));
                    segmentModel.setStartTimeInMillis(
                            mSegmentsCursor.getLong(mSegmentsCursor.getColumnIndex(Segments.START_TIME)));
                    segmentModel.setEndTimeInMillis(
                            mSegmentsCursor.getLong(mSegmentsCursor.getColumnIndex(Segments.END_TIME)));
                    trackModel.addSegment(segmentModel);
                }
            }
        }
    }
    return trackModel;
}

From source file:com.android.bluetooth.map.BluetoothMapContent.java

private void setSenderAddressing(BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi,
        BluetoothMapAppParams ap) {/*from w w  w .j av a2 s.c o  m*/
    if ((ap.getParameterMask() & MASK_SENDER_ADDRESSING) != 0) {
        String address = null;
        if (fi.msgType == FilterInfo.TYPE_SMS) {
            int msgType = c.getInt(c.getColumnIndex(Sms.TYPE));
            if (msgType == 1) {
                address = c.getString(c.getColumnIndex(Sms.ADDRESS));
            } else {
                address = fi.phoneNum;
            }
        } else if (fi.msgType == FilterInfo.TYPE_MMS) {
            long id = c.getLong(c.getColumnIndex(BaseColumns._ID));
            address = getAddressMms(mResolver, id, MMS_FROM);
        } else {
            int fromIndex = c.getColumnIndex(MessageColumns.FROM_LIST);
            address = c.getString(fromIndex);
            if (address != null) {
                if (address.contains("")) {
                    String[] senderAddrStr = address.split("");
                    if (senderAddrStr != null && senderAddrStr.length > 0) {
                        if (V) {
                            Log.v(TAG, " ::Sender Addressing split String 0:: " + senderAddrStr[0]
                                    + "::Sender Addressing split String 1:: " + senderAddrStr[1]);
                        }
                        e.setEmailSenderAddressing(senderAddrStr[0].trim());
                    }
                } else {
                    if (address.indexOf('<') != -1 && address.indexOf('>') != -1) {
                        if (D)
                            Log.d(TAG, "setSenderAddressing: "
                                    + address.substring(address.indexOf('<') + 1, address.lastIndexOf('>')));
                        e.setEmailSenderAddressing(
                                address.substring(address.indexOf('<') + 1, address.lastIndexOf('>')));
                    } else {
                        if (D)
                            Log.d(TAG, "setSenderAddressing: " + address);
                        e.setEmailSenderAddressing(address);
                    }
                }
            }
            return;
        }
        if (D)
            Log.d(TAG, "setSenderAddressing: " + address);
        e.setSenderAddressing(address);
    }
}

From source file:org.getlantern.firetweet.util.Utils.java

public static synchronized void cleanDatabasesByItemLimit(final Context context) {
    if (context == null)
        return;/* ww w  .j a  v  a 2 s.c o  m*/
    final ContentResolver resolver = context.getContentResolver();
    final int itemLimit = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getInt(KEY_DATABASE_ITEM_LIMIT, DEFAULT_DATABASE_ITEM_LIMIT);

    for (final long account_id : getAccountIds(context)) {
        // Clean statuses.
        for (final Uri uri : STATUSES_URIS) {
            if (CachedStatuses.CONTENT_URI.equals(uri)) {
                continue;
            }
            final String table = getTableNameByUri(uri);
            final Expression account_where = new Expression(Statuses.ACCOUNT_ID + " = " + account_id);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(Statuses._ID)).from(new Tables(table));
            qb.where(Expression.equals(Statuses.ACCOUNT_ID, account_id));
            qb.orderBy(new OrderBy(Statuses.STATUS_ID, false));
            qb.limit(itemLimit);
            final Expression where = Expression.and(Expression.notIn(new Column(Statuses._ID), qb.build()),
                    account_where);
            resolver.delete(uri, where.getSQL(), null);
        }
        for (final Uri uri : DIRECT_MESSAGES_URIS) {
            final String table = getTableNameByUri(uri);
            final Expression account_where = new Expression(DirectMessages.ACCOUNT_ID + " = " + account_id);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(DirectMessages._ID)).from(new Tables(table));
            qb.where(Expression.equals(DirectMessages.ACCOUNT_ID, account_id));
            qb.orderBy(new OrderBy(DirectMessages.MESSAGE_ID, false));
            qb.limit(itemLimit);
            final Expression where = Expression
                    .and(Expression.notIn(new Column(DirectMessages._ID), qb.build()), account_where);
            resolver.delete(uri, where.getSQL(), null);
        }
    }
    // Clean cached values.
    for (final Uri uri : CACHE_URIS) {
        final String table = getTableNameByUri(uri);
        if (table == null)
            continue;
        final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
        qb.select(new Column(BaseColumns._ID));
        qb.from(new Tables(table));
        qb.orderBy(new OrderBy(BaseColumns._ID, false));
        qb.limit(itemLimit * 20);
        final Expression where = Expression.notIn(new Column(BaseColumns._ID), qb.build());
        resolver.delete(uri, where.getSQL(), null);
    }
}

From source file:org.opendatakit.tables.utils.CollectUtil.java

/**
 * Return the URI of the form for adding a row to a table. If the formId is
 * custom defined it must exist to Collect (most likely by putting the form in
 * Collect's form folder and starting Collect once). If the form does not
 * exist, it inserts the static addRowForm information into Collect.
 * <p>//from  w w w.  j av  a2 s. com
 * Display name only matters if it is a programmatically generated form.
 * <p>
 * Precondition: If formId refers to a custom form, it must have already been
 * scanned in and known to exist to Collect. If the formId is not custom, but
 * refers to a form built on the fly, it should be the id of
 * {@link COLLECT_ADDROW_FORM_ID}, and the form should already have been
 * written.
 *
 * @param resolver
 *          ContentResolver of the calling activity
 * @param appName
 *          application name.
 * @param formId
 *          id of the form whose uri will be returned
 * @param formDisplayName
 *          display name of the table. Only pertinent if the form has been
 *          programmatically generated.
 * @return the uri of the form.
 */
private static Uri getUriOfForm(ContentResolver resolver, String appName, String formId) {
    Uri resultUri = null;
    Cursor c = null;
    try {
        c = resolver.query(CollectUtil.CONTENT_FORM_URI, null, CollectUtil.COLLECT_KEY_JR_FORM_ID + "=?",
                new String[] { formId }, null);
        if (!c.moveToFirst()) {
            WebLogger.getLogger(appName).e(TAG, "query of Collect for form returned no results");
        } else {
            // we got a result, meaning that the form exists in collect.
            // so we just need to set the URI.
            int collectFormKey; // this is the primary key of the form in
            // Collect's
            // database.
            collectFormKey = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class,
                    c.getColumnIndexOrThrow(BaseColumns._ID));
            resultUri = (Uri.parse(CollectUtil.CONTENT_FORM_URI + "/" + collectFormKey));
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
    return resultUri;
}

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

private File getCacheFileForArtworkUri(Uri artworkUri) {
    Context context = getContext();
    if (context == null || artworkUri == null) {
        return null;
    }/*ww  w .j a  va  2s . com*/
    File directory = new File(context.getFilesDir(), "artwork");
    if (!directory.exists() && !directory.mkdirs()) {
        return null;
    }
    String[] projection = { BaseColumns._ID, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI,
            MuzeiContract.Artwork.COLUMN_NAME_TOKEN };
    Cursor data = queryArtwork(artworkUri, projection, null, null, null);
    if (data == null) {
        return null;
    }
    if (!data.moveToFirst()) {
        Log.e(TAG, "Invalid artwork URI " + artworkUri);
        return null;
    }
    // While normally we'd use data.getLong(), we later need this as a String so the automatic conversion helps here
    String id = data.getString(0);
    String imageUri = data.getString(1);
    String token = data.getString(2);
    data.close();
    if (TextUtils.isEmpty(imageUri) && TextUtils.isEmpty(token)) {
        return new File(directory, id);
    }
    // Otherwise, create a unique filename based on the imageUri and token
    StringBuilder filename = new StringBuilder();
    if (!TextUtils.isEmpty(imageUri)) {
        Uri uri = Uri.parse(imageUri);
        filename.append(uri.getScheme()).append("_").append(uri.getHost()).append("_");
        String encodedPath = uri.getEncodedPath();
        if (!TextUtils.isEmpty(encodedPath)) {
            int length = encodedPath.length();
            if (length > 60) {
                encodedPath = encodedPath.substring(length - 60);
            }
            encodedPath = encodedPath.replace('/', '_');
            filename.append(encodedPath).append("_");
        }
    }
    // Use the imageUri if available, otherwise use the token
    String unique = !TextUtils.isEmpty(imageUri) ? imageUri : token;
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(unique.getBytes("UTF-8"));
        byte[] digest = md.digest();
        for (byte b : digest) {
            if ((0xff & b) < 0x10) {
                filename.append("0").append(Integer.toHexString((0xFF & b)));
            } else {
                filename.append(Integer.toHexString(0xFF & b));
            }
        }
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        filename.append(unique.hashCode());
    }
    return new File(directory, filename.toString());
}

From source file:com.android.bluetooth.map.BluetoothMapContent.java

private void setSenderName(BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi,
        BluetoothMapAppParams ap) {//www .j  a  v  a2s  .  c  om
    if ((ap.getParameterMask() & MASK_SENDER_NAME) != 0) {
        String name = "";
        if (fi.msgType == FilterInfo.TYPE_SMS) {
            int msgType = c.getInt(c.getColumnIndex(Sms.TYPE));
            if (msgType == 1) {
                String phone = c.getString(c.getColumnIndex(Sms.ADDRESS));
                name = getContactNameFromPhone(phone);
            } else {
                name = fi.phoneAlphaTag;
            }
        } else if (fi.msgType == FilterInfo.TYPE_MMS) {
            long id = c.getLong(c.getColumnIndex(BaseColumns._ID));
            String phone = getAddressMms(mResolver, id, MMS_FROM);
            name = getContactNameFromPhone(phone);
        } else { //email case
            int displayNameIndex = c.getColumnIndex(MessageColumns.DISPLAY_NAME);
            if (D)
                Log.d(TAG, "setSenderName: " + c.getString(displayNameIndex));
            name = c.getString(displayNameIndex);
            if (name != null && name.contains("")) {
                String[] senderStr = name.split("");
                if (senderStr != null && senderStr.length > 0) {
                    if (V) {
                        Log.v(TAG, " ::Sender name split String 0:: " + senderStr[0]
                                + "::Sender name split String 1:: " + senderStr[1]);
                    }
                    name = senderStr[1];
                }
            }
            if (name != null) {
                name = decodeEncodedWord(name);
                name = name.trim();
            }

        }
        if (D)
            Log.d(TAG, "setSenderName: " + name);
        e.setSenderName(name);
    }
}

From source file:org.mariotaku.twidere.util.DataStoreUtils.java

public static synchronized void cleanDatabasesByItemLimit(final Context context) {
    if (context == null)
        return;/*from www .  j  av a 2 s . c o m*/
    final ContentResolver resolver = context.getContentResolver();
    final int itemLimit = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getInt(KEY_DATABASE_ITEM_LIMIT, DEFAULT_DATABASE_ITEM_LIMIT);

    for (final UserKey accountKey : getAccountKeys(context)) {
        // Clean statuses.
        for (final Uri uri : STATUSES_URIS) {
            if (CachedStatuses.CONTENT_URI.equals(uri)) {
                continue;
            }
            final String table = getTableNameByUri(uri);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(Statuses._ID)).from(new Tables(table))
                    .where(Expression.equalsArgs(Statuses.ACCOUNT_KEY))
                    .orderBy(new OrderBy(Statuses.POSITION_KEY, false)).limit(itemLimit);
            final Expression where = Expression.and(Expression.notIn(new Column(Statuses._ID), qb.build()),
                    Expression.equalsArgs(Statuses.ACCOUNT_KEY));
            final String[] whereArgs = { String.valueOf(accountKey), String.valueOf(accountKey) };
            resolver.delete(uri, where.getSQL(), whereArgs);
        }
        for (final Uri uri : ACTIVITIES_URIS) {
            final String table = getTableNameByUri(uri);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(Activities._ID)).from(new Tables(table))
                    .where(Expression.equalsArgs(Activities.ACCOUNT_KEY))
                    .orderBy(new OrderBy(Activities.TIMESTAMP, false)).limit(itemLimit);
            final Expression where = Expression.and(Expression.notIn(new Column(Activities._ID), qb.build()),
                    Expression.equalsArgs(Activities.ACCOUNT_KEY));
            final String[] whereArgs = { String.valueOf(accountKey), String.valueOf(accountKey) };
            resolver.delete(uri, where.getSQL(), whereArgs);
        }
        for (final Uri uri : DIRECT_MESSAGES_URIS) {
            final String table = getTableNameByUri(uri);
            final Expression accountWhere = Expression.equalsArgs(DirectMessages.ACCOUNT_KEY);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(DirectMessages._ID)).from(new Tables(table)).where(accountWhere)
                    .orderBy(new OrderBy(DirectMessages.MESSAGE_ID, false)).limit(itemLimit * 10);
            final Expression where = Expression.and(
                    Expression.notIn(new Column(DirectMessages._ID), qb.build()),
                    Expression.equalsArgs(DirectMessages.ACCOUNT_KEY));
            final String[] whereArgs = { String.valueOf(accountKey), String.valueOf(accountKey) };
            resolver.delete(uri, where.getSQL(), whereArgs);
        }
    }
    // Clean cached values.
    for (final Uri uri : CACHE_URIS) {
        final String table = getTableNameByUri(uri);
        if (table == null)
            continue;
        final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
        qb.select(new Column(BaseColumns._ID)).from(new Tables(table))
                .orderBy(new OrderBy(BaseColumns._ID, false)).limit(itemLimit * 20);
        final Expression where = Expression.notIn(new Column(BaseColumns._ID), qb.build());
        resolver.delete(uri, where.getSQL(), null);
    }
}

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

/**
 * Limit the number of cached files per art source to {@link #MAX_CACHE_SIZE}.
 * @see #MAX_CACHE_SIZE/*  www . j  av a  2  s. co  m*/
 */
private void cleanupCachedFiles() {
    Context context = getContext();
    if (context == null) {
        return;
    }
    Cursor sources = querySource(MuzeiContract.Sources.CONTENT_URI,
            new String[] { MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME }, null, null, null);
    if (sources == null) {
        return;
    }
    // Access to certain artwork can be persisted through MuzeiDocumentsProvider
    // We never want to delete these artwork as that would break other apps
    Set<Uri> persistedUris = MuzeiDocumentsProvider.getPersistedArtworkUris(context);
    // Loop through each source, cleaning up old artwork
    while (sources.moveToNext()) {
        String componentName = sources.getString(0);
        // Now use that ComponentName to look through the past artwork from that source
        Cursor artworkBySource = queryArtwork(MuzeiContract.Artwork.CONTENT_URI,
                new String[] { BaseColumns._ID, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI,
                        MuzeiContract.Artwork.COLUMN_NAME_TOKEN },
                MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME + "=?", new String[] { componentName },
                MuzeiContract.Artwork.COLUMN_NAME_DATE_ADDED + " DESC");
        if (artworkBySource == null) {
            continue;
        }
        List<String> artworkIdsToKeep = new ArrayList<>();
        List<String> artworkToKeep = new ArrayList<>();
        // First find all of the persisted artwork from this source and mark them as artwork to keep
        while (artworkBySource.moveToNext()) {
            long id = artworkBySource.getLong(0);
            Uri uri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, id);
            String artworkUri = artworkBySource.getString(1);
            String artworkToken = artworkBySource.getString(2);
            String unique = !TextUtils.isEmpty(artworkUri) ? artworkUri : artworkToken;
            if (persistedUris.contains(uri)) {
                // Always keep artwork that is persisted
                artworkIdsToKeep.add(Long.toString(id));
                artworkToKeep.add(unique);
            }
        }
        // Now go through the artwork from this source and find the most recent artwork
        // and mark them as artwork to keep
        int count = 0;
        artworkBySource.moveToPosition(-1);
        while (artworkBySource.moveToNext()) {
            // BaseColumns._ID is a long, but we need it as a String later anyways
            String id = artworkBySource.getString(0);
            String artworkUri = artworkBySource.getString(1);
            String artworkToken = artworkBySource.getString(2);
            String unique = !TextUtils.isEmpty(artworkUri) ? artworkUri : artworkToken;
            if (artworkToKeep.contains(unique)) {
                // This ensures we are double counting the same artwork in our count
                artworkIdsToKeep.add(id);
                continue;
            }
            if (count++ < MAX_CACHE_SIZE) {
                // Keep artwork below the MAX_CACHE_SIZE
                artworkIdsToKeep.add(id);
                artworkToKeep.add(unique);
            }
        }
        // Now delete all artwork not in the keep list
        int numDeleted = deleteArtwork(MuzeiContract.Artwork.CONTENT_URI,
                MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME + "=?" + " AND "
                        + MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " NOT IN ("
                        + TextUtils.join(",", artworkIdsToKeep) + ")",
                new String[] { componentName });
        if (numDeleted > 0) {
            Log.d(TAG, "For " + componentName + " kept " + artworkToKeep.size() + " artwork, deleted "
                    + numDeleted);
        }
        artworkBySource.close();
    }
    sources.close();
}

From source file:com.android.bluetooth.map.BluetoothMapContent.java

private void setSubject(BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi,
        BluetoothMapAppParams ap) {/*from   w w w  . j a va  2s  .c  o m*/
    String subject = "";
    int subLength = ap.getSubjectLength();
    if (subLength == BluetoothMapAppParams.INVALID_VALUE_PARAMETER)
        subLength = 256;

    if (BluetoothMapService.getRemoteDevice().getAddress().startsWith(HONDA_CARKIT)
            || (ap.getParameterMask() & MASK_SUBJECT) != 0) {
        if (fi.msgType == FilterInfo.TYPE_SMS) {
            subject = c.getString(c.getColumnIndex(Sms.BODY));
        } else if (fi.msgType == FilterInfo.TYPE_MMS) {
            subject = c.getString(c.getColumnIndex(Mms.SUBJECT));
            if (subject == null || subject.length() == 0) {
                /* Get subject from mms text body parts - if any exists */
                long id = c.getLong(c.getColumnIndex(BaseColumns._ID));
                subject = getTextPartsMms(id);
            }
        } else {
            subject = c.getString(c.getColumnIndex(MessageColumns.SUBJECT));
            if (subject == null || subject.length() == 0) {
                /* Get subject from mms text body parts - if any exists */
                long id = c.getLong(c.getColumnIndex(BaseColumns._ID));
                subject = getTextPartsEmail(id);
            }
        }
        if (subject != null) {
            subject = subject.substring(0, Math.min(subject.length(), subLength));
        }
        if (D)
            Log.d(TAG, "setSubject: " + subject);
        e.setSubject(subject);
    }
}