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:com.andrew.apollo.utils.MusicUtils.java

/**
 * Returns the ID for an album.//from  ww  w .j  a va2  s. c  o  m
 *
 * @param context The {@link Context} to use.
 * @param albumName The name of the album.
 * @param artistName The name of the artist
 * @return The ID for an album.
 */
public static long getIdForAlbum(final Context context, final String albumName, final String artistName) {
    Cursor cursor;
    try {
        cursor = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                new String[] { BaseColumns._ID }, AlbumColumns.ALBUM + "=? AND " + AlbumColumns.ARTIST + "=?",
                new String[] { albumName, artistName }, AlbumColumns.ALBUM);
    } catch (Throwable t) {
        return -1;
    }

    int id = -1;
    id = getFirstId(cursor, id);
    return id;
}

From source file:ru.valle.safetrade.SellActivity.java

private void checkConfirmationCodeToDecodeAddress(final String confirmationCode) {
    final String password = tradeInfo.password;
    final long id = rowId;
    confirmationCodeDecodingTask = new AsyncTask<Void, String, String>() {
        public ProgressDialog progressDialog;

        @Override//www . ja  v a2s  . c om
        protected void onPreExecute() {
            final CharSequence oldEnteredValue = confirmationCodeView.getText();
            confirmationCodeView.setText(confirmationCode);
            progressDialog = ProgressDialog.show(SellActivity.this, null,
                    getString(R.string.decoding_confirmation_code_using_password), true);
            progressDialog.setCancelable(true);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    confirmationCodeDecodingTask.cancel(true);
                    confirmationCodeView.setText(oldEnteredValue);
                    if (rowId != -1) {
                        loadState(rowId);
                    }
                }
            });
        }

        @Override
        protected void onProgressUpdate(String... values) {
            try {
                progressDialog.setMessage(values[0]);
            } catch (Exception ignored) {
            }
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                String address = BTCUtils.bip38DecryptConfirmation(confirmationCode, password);
                if (address != null) {
                    SQLiteDatabase db = DatabaseHelper.getInstance(SellActivity.this).getWritableDatabase();
                    if (db != null) {
                        ContentValues cv = new ContentValues();
                        cv.put(DatabaseHelper.COLUMN_ADDRESS, address);
                        cv.put(DatabaseHelper.COLUMN_CONFIRMATION_CODE, confirmationCode);
                        db.update(DatabaseHelper.TABLE_HISTORY, cv, BaseColumns._ID + "=?",
                                new String[] { String.valueOf(id) });
                    }
                }
                return address;
            } catch (Throwable e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(final String address) {
            try {
                progressDialog.dismiss();
            } catch (Exception ignored) {
            }
            confirmationCodeDecodingTask = null;
            if (!TextUtils.isEmpty(address)) {
                confirmationCodeView.setText(confirmationCode);
                addressView.setText(address);
                addressLabelView.setVisibility(View.VISIBLE);
                addressView.setVisibility(View.VISIBLE);
                MainActivity.updateBalance(SellActivity.this, id, address, onAddressStateReceivedListener);
            } else {
                loadState(rowId);
                showAlert(getString(R.string.confirmation_code_doesnt_match));
            }
        }
    }.execute();
}

From source file:edu.mit.mobile.android.locast.data.MediaSync.java

/**
 * Scans the media database to see if the given item is currently there. If
 * it is, update the cast media to point to the local content: URI for it.
 *
 * @param context//from   w ww. j a  v a2  s .  c om
 * @param castMedia
 *            Local URI to the cast.
 * @param pubUri
 *            public URI to the media file.
 * @return local URI if it exists.
 * @throws SyncException
 */
public String checkForMediaEntry(Uri castMedia, Uri pubUri, String mimeType) throws SyncException {
    final ContentResolver cr = getContentResolver();

    String newLocUri = null;
    final File destfile = getFilePath(pubUri);

    if (mimeType == null) {
        throw new SyncException("missing MIME type");
    }

    String[] projection;
    String selection;
    Uri contentUri;

    if (mimeType.startsWith("image/")) {
        projection = new String[] { Images.Media._ID, Images.Media.DATA };
        selection = Images.Media.DATA + "=?";
        contentUri = Images.Media.EXTERNAL_CONTENT_URI;

    } else if (mimeType.startsWith("video/")) {
        projection = new String[] { Video.Media._ID, Video.Media.DATA };
        selection = Video.Media.DATA + "=?";
        contentUri = Video.Media.EXTERNAL_CONTENT_URI;

    } else {
        throw new SyncException("unknown MIME type: '" + mimeType + "'");
    }

    final String[] selectionArgs = { destfile.getAbsolutePath() };

    final Cursor mediaEntry = cr.query(contentUri, projection, selection, selectionArgs, null);
    try {
        if (mediaEntry.moveToFirst()) {
            newLocUri = ContentUris
                    .withAppendedId(contentUri, mediaEntry.getLong(mediaEntry.getColumnIndex(BaseColumns._ID)))
                    .toString();
        }
    } finally {
        mediaEntry.close();
    }

    if (newLocUri != null) {
        updateCastMediaLocalUri(castMedia, newLocUri, mimeType);
    } else {
        Log.e(TAG, "The media provider doesn't seem to know about " + destfile.getAbsolutePath()
                + " which is on the filesystem. Strange...");
    }
    return newLocUri;
}

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

private void setText(BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, BluetoothMapAppParams ap) {
    if ((ap.getParameterMask() & MASK_TEXT) != 0) {
        String hasText = "";
        if (fi.msgType == FilterInfo.TYPE_SMS) {
            hasText = "yes";
        } else if (fi.msgType == FilterInfo.TYPE_MMS) {
            int textOnly = c.getInt(c.getColumnIndex(Mms.TEXT_ONLY));
            if (textOnly == 1) {
                hasText = "yes";
            } else {
                long id = c.getLong(c.getColumnIndex(BaseColumns._ID));
                String text = getTextPartsMms(id);
                if (text != null && text.length() > 0) {
                    hasText = "yes";
                } else {
                    hasText = "no";
                }/*  w  w w.j ava  2s  .co  m*/
            }
        } else {
            hasText = "yes";
        }
        if (D)
            Log.d(TAG, "setText: " + hasText);
        e.setText(hasText);
    }
}

From source file:org.kontalk.provider.UsersProvider.java

/** Triggers a complete resync of the users database. */
private int resync() {
    Context context = getContext();
    ContentResolver cr = context.getContentResolver();
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    // begin transaction
    beginTransaction(db);/*from  w w  w  .j  av a  2  s.  c o  m*/
    boolean success = false;

    int count = 0;

    // delete old users content
    try {
        db.execSQL("DELETE FROM " + TABLE_USERS_OFFLINE);
    } catch (SQLException e) {
        // table might not exist - create it! (shouldn't happen since version 4)
        db.execSQL(DatabaseHelper.SCHEMA_USERS_OFFLINE);
    }

    // we are trying to be fast here
    SQLiteStatement stm = db.compileStatement("INSERT INTO " + TABLE_USERS_OFFLINE
            + " (number, jid, display_name, lookup_key, contact_id, registered)" + " VALUES(?, ?, ?, ?, ?, ?)");

    // these two statements are used to immediately update data in the online table
    // even if the data is dummy, it will be soon replaced by sync or by manual request
    SQLiteStatement onlineUpd = db.compileStatement("UPDATE " + TABLE_USERS
            + " SET number = ?, display_name = ?, lookup_key = ?, contact_id = ? WHERE jid = ?");
    SQLiteStatement onlineIns = db.compileStatement("INSERT INTO " + TABLE_USERS
            + " (number, jid, display_name, lookup_key, contact_id, registered)" + " VALUES(?, ?, ?, ?, ?, ?)");

    Cursor phones = null;
    String dialPrefix = Preferences.getDialPrefix();
    int dialPrefixLen = dialPrefix != null ? dialPrefix.length() : 0;

    try {
        String where = !Preferences.getSyncInvisibleContacts(context)
                ? ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1 AND "
                : "";

        // query for phone numbers
        phones = cr.query(Phone.CONTENT_URI, new String[] { Phone.NUMBER, Phone.DISPLAY_NAME, Phone.LOOKUP_KEY,
                Phone.CONTACT_ID, RawContacts.ACCOUNT_TYPE }, where + " (" +
        // this will filter out RawContacts from Kontalk
                        RawContacts.ACCOUNT_TYPE + " IS NULL OR " + RawContacts.ACCOUNT_TYPE
                        + " NOT IN (?, ?))",
                new String[] { Authenticator.ACCOUNT_TYPE, Authenticator.ACCOUNT_TYPE_LEGACY }, null);

        if (phones != null) {
            while (phones.moveToNext()) {
                String number = phones.getString(0);
                String name = phones.getString(1);

                // buggy provider - skip entry
                if (name == null || number == null)
                    continue;

                // remove dial prefix first
                if (dialPrefix != null && number.startsWith(dialPrefix))
                    number = number.substring(dialPrefixLen);

                // a phone number with less than 4 digits???
                if (number.length() < 4)
                    continue;

                // fix number
                try {
                    number = NumberValidator.fixNumber(context, number,
                            Authenticator.getDefaultAccountName(context), 0);
                } catch (Exception e) {
                    Log.e(SyncAdapter.TAG, "unable to normalize number: " + number + " - skipping", e);
                    // skip number
                    continue;
                }

                try {
                    String hash = MessageUtils.sha1(number);
                    String lookupKey = phones.getString(2);
                    long contactId = phones.getLong(3);
                    String jid = XMPPUtils.createLocalJID(getContext(), hash);

                    addResyncContact(db, stm, onlineUpd, onlineIns, number, jid, name, lookupKey, contactId,
                            false);
                    count++;
                } catch (IllegalArgumentException iae) {
                    Log.w(SyncAdapter.TAG, "doing sync with no server?");
                } catch (SQLiteConstraintException sqe) {
                    // skip duplicate number
                }
            }

            phones.close();
        } else {
            Log.e(SyncAdapter.TAG, "query to contacts failed!");
        }

        if (Preferences.getSyncSIMContacts(getContext())) {
            // query for SIM contacts
            // column selection doesn't work because of a bug in Android
            // TODO this is a bit unclear...
            try {
                phones = cr.query(Uri.parse("content://icc/adn/"), null, null, null, null);
            } catch (Exception e) {
                /*
                On some phones:
                java.lang.NullPointerException
                at android.os.Parcel.readException(Parcel.java:1431)
                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
                at android.content.ContentProviderProxy.query(ContentProviderNative.java:366)
                at android.content.ContentResolver.query(ContentResolver.java:372)
                at android.content.ContentResolver.query(ContentResolver.java:315)
                 */
                Log.w(SyncAdapter.TAG, "unable to retrieve SIM contacts", e);
                phones = null;
            }

            if (phones != null) {
                while (phones.moveToNext()) {
                    String name = phones.getString(phones.getColumnIndex("name"));
                    String number = phones.getString(phones.getColumnIndex("number"));
                    // buggy firmware - skip entry
                    if (name == null || number == null)
                        continue;

                    // remove dial prefix first
                    if (dialPrefix != null && number.startsWith(dialPrefix))
                        number = number.substring(dialPrefixLen);

                    // a phone number with less than 4 digits???
                    if (number.length() < 4)
                        continue;

                    // fix number
                    try {
                        number = NumberValidator.fixNumber(context, number,
                                Authenticator.getDefaultAccountName(context), 0);
                    } catch (Exception e) {
                        Log.e(SyncAdapter.TAG, "unable to normalize number: " + number + " - skipping", e);
                        // skip number
                        continue;
                    }

                    try {
                        String hash = MessageUtils.sha1(number);
                        String jid = XMPPUtils.createLocalJID(getContext(), hash);
                        long contactId = phones.getLong(phones.getColumnIndex(BaseColumns._ID));

                        addResyncContact(db, stm, onlineUpd, onlineIns, number, jid, name, null, contactId,
                                false);
                        count++;
                    } catch (IllegalArgumentException iae) {
                        Log.w(SyncAdapter.TAG, "doing sync with no server?");
                    } catch (SQLiteConstraintException sqe) {
                        // skip duplicate number
                    }
                }
            }
        }

        // try to add account number with display name
        String ownNumber = Authenticator.getDefaultAccountName(getContext());
        if (ownNumber != null) {
            String ownName = Authenticator.getDefaultDisplayName(getContext());
            String fingerprint = null;
            byte[] publicKeyData = null;
            try {
                PersonalKey myKey = Kontalk.get(getContext()).getPersonalKey();
                if (myKey != null) {
                    fingerprint = myKey.getFingerprint();
                    publicKeyData = myKey.getEncodedPublicKeyRing();
                }
            } catch (Exception e) {
                Log.w(SyncAdapter.TAG, "unable to load personal key", e);
            }
            try {
                String hash = MessageUtils.sha1(ownNumber);
                String jid = XMPPUtils.createLocalJID(getContext(), hash);

                addResyncContact(db, stm, onlineUpd, onlineIns, ownNumber, jid, ownName, null, null, true);
                insertOrUpdateKey(jid, fingerprint, publicKeyData, false);
                count++;
            } catch (IllegalArgumentException iae) {
                Log.w(SyncAdapter.TAG, "doing sync with no server?");
            } catch (SQLiteConstraintException sqe) {
                // skip duplicate number
            }
        }

        success = setTransactionSuccessful(db);
    } finally {
        endTransaction(db, success);
        if (phones != null)
            phones.close();
        stm.close();

        // time to invalidate contacts cache (because of updates to online)
        Contact.invalidate();
    }
    return count;
}

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

public static synchronized void cleanDatabasesByItemLimit(final Context context) {
    if (context == null)
        return;/*from w  ww. j  ava2s.  c  o  m*/
    final ContentResolver resolver = context.getContentResolver();
    final int item_limit = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getInt(PREFERENCE_KEY_DATABASE_ITEM_LIMIT, PREFERENCE_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 StringBuilder where = new StringBuilder();
            where.append(Statuses.ACCOUNT_ID + " = " + account_id);
            where.append(" AND ");
            where.append(Statuses._ID + " NOT IN (");
            where.append(" SELECT " + Statuses._ID + " FROM " + table);
            where.append(" WHERE " + Statuses.ACCOUNT_ID + " = " + account_id);
            where.append(" ORDER BY " + Statuses.STATUS_ID + " DESC");
            where.append(" LIMIT " + item_limit + ")");
            resolver.delete(uri, where.toString(), null);
        }
        for (final Uri uri : DIRECT_MESSAGES_URIS) {
            final String table = getTableNameByUri(uri);
            final StringBuilder where = new StringBuilder();
            where.append(DirectMessages.ACCOUNT_ID + " = " + account_id);
            where.append(" AND ");
            where.append(DirectMessages._ID + " NOT IN (");
            where.append(" SELECT " + DirectMessages._ID + " FROM " + table);
            where.append(" WHERE " + DirectMessages.ACCOUNT_ID + " = " + account_id);
            where.append(" ORDER BY " + DirectMessages.MESSAGE_ID + " DESC");
            where.append(" LIMIT " + item_limit + ")");
            resolver.delete(uri, where.toString(), null);
        }
    }
    // Clean cached values.
    for (final Uri uri : CACHE_URIS) {
        final String table = getTableNameByUri(uri);
        final StringBuilder where = new StringBuilder();
        where.append(Statuses._ID + " NOT IN (");
        where.append(" SELECT " + BaseColumns._ID + " FROM " + table);
        where.append(" LIMIT " + (int) (Math.sqrt(item_limit) * 100) + ")");
        resolver.delete(uri, where.toString(), null);
    }
}

From source file:com.esri.android.mapsapp.MapFragment.java

/**
 * Initialize Suggestion Cursor/*from  www . j  a v  a2 s. c o m*/
 */
private void initSuggestionCursor() {
    String[] cols = new String[] { BaseColumns._ID, COLUMN_NAME_ADDRESS, COLUMN_NAME_X, COLUMN_NAME_Y };
    mSuggestionCursor = new MatrixCursor(cols);
}

From source file:ru.valle.safetrade.SellActivity.java

private void loadState(final long id) {
    cancelAllTasks();//from  w w w  .  ja v  a 2 s .  c  o m
    loadStateTask = new AsyncTask<Void, Void, TradeRecord>() {
        @Override
        protected TradeRecord doInBackground(Void... params) {
            SQLiteDatabase db = DatabaseHelper.getInstance(SellActivity.this).getReadableDatabase();
            if (db != null) {
                Cursor cursor = db.query(DatabaseHelper.TABLE_HISTORY, null, BaseColumns._ID + "=?",
                        new String[] { String.valueOf(id) }, null, null, null);
                ArrayList<TradeRecord> tradeRecords = DatabaseHelper.readTradeRecords(cursor);
                return tradeRecords.isEmpty() ? null : tradeRecords.get(0);
            } else {
                return null;
            }
        }

        @Override
        protected void onPostExecute(final TradeRecord tradeRecord) {
            tradeInfo = tradeRecord;
            loadStateTask = null;
            rowId = tradeRecord.id;
            passwordView.setText(tradeRecord.password);
            intermediateCodeView.setText(tradeRecord.intermediateCode);
            if (confirmationCodeDecodingTask == null) {
                confirmationCodeView.setText(tradeRecord.confirmationCode);
            }
            if (TextUtils.isEmpty(tradeRecord.address)) {
                addressLabelView.setVisibility(View.GONE);
                addressView.setVisibility(View.GONE);
            } else {
                addressView.setText(tradeRecord.address);
                addressLabelView.setVisibility(View.VISIBLE);
                addressView.setVisibility(View.VISIBLE);
            }
            finalAddressView.setText(tradeRecord.destinationAddress);
            if (privateKeyDecodingTask == null) {
                privateKeyView.setText(tradeRecord.encryptedPrivateKey);
            }
            MainActivity.updateBalance(SellActivity.this, id, tradeInfo.address,
                    onAddressStateReceivedListener);
        }
    };
    if (Build.VERSION.SDK_INT >= 11) {
        loadStateTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {
        loadStateTask.execute();
    }
}

From source file:com.andrew.apollo.utils.MusicUtils.java

public static List<Playlist> getPlaylists(final Context context) {
    final List<Playlist> result = new ArrayList<>();
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[] { BaseColumns._ID, MediaStore.Audio.PlaylistsColumns.NAME };

    try {/*w ww.  j  av a2s. c o  m*/
        final Cursor cursor = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection, null,
                null, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    result.add(new Playlist(cursor.getLong(0), cursor.getString(1)));
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
    } catch (Throwable e) {
        LOG.error("Could not fetch playlists", e);
    }

    return result;
}

From source file:com.google.android.apps.muzei.gallery.GallerySettingsActivity.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader(this, GalleryContract.ChosenPhotos.CONTENT_URI,
            new String[] { BaseColumns._ID, GalleryContract.ChosenPhotos.COLUMN_NAME_URI }, null, null, null);
}