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.google.android.apps.muzei.provider.MuzeiProvider.java

private int deleteArtwork(@NonNull final Uri uri, final String selection, final String[] selectionArgs) {
    // Opens the database object in "write" mode.
    final SQLiteDatabase db = databaseHelper.getWritableDatabase();
    String finalWhere = selection;
    if (MuzeiProvider.uriMatcher.match(uri) == ARTWORK_ID) {
        finalWhere = MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " = "
                + uri.getLastPathSegment();
        // If there were additional selection criteria, append them to the final WHERE clause
        if (selection != null)
            finalWhere = finalWhere + " AND " + selection;
    }/*from   w ww  .  j  av  a  2 s .  c om*/
    // We can't just simply delete the rows as that won't free up the space occupied by the
    // artwork image files associated with each row being deleted. Instead we have to query
    // and manually delete each artwork file
    String[] projection = new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID,
            MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI, MuzeiContract.Artwork.COLUMN_NAME_TOKEN };
    Cursor rowsToDelete = queryArtwork(uri, projection, finalWhere, selectionArgs,
            MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI);
    if (rowsToDelete == null) {
        return 0;
    }
    // First we build a list of IDs to be deleted. This will be used if we need to determine
    // if a given image URI needs to be deleted
    List<String> idsToDelete = new ArrayList<>();
    rowsToDelete.moveToFirst();
    while (!rowsToDelete.isAfterLast()) {
        idsToDelete.add(Long.toString(rowsToDelete.getLong(0)));
        rowsToDelete.moveToNext();
    }
    String notInDeleteIds = MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " NOT IN ("
            + TextUtils.join(",", idsToDelete) + ")";
    // Now we actually go through the list of rows to be deleted
    // and check if we can delete the artwork image file associated with each one
    rowsToDelete.moveToFirst();
    while (!rowsToDelete.isAfterLast()) {
        Uri artworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, rowsToDelete.getLong(0));
        String imageUri = rowsToDelete.getString(1);
        String token = rowsToDelete.getString(2);
        if (TextUtils.isEmpty(imageUri) && TextUtils.isEmpty(token)) {
            // An empty image URI and token means the artwork is unique to this specific row
            // so we can always delete it when the associated row is deleted
            File artwork = getCacheFileForArtworkUri(artworkUri);
            if (artwork != null && artwork.exists()) {
                artwork.delete();
            }
        } else if (TextUtils.isEmpty(imageUri)) {
            // Check if there are other rows using this same token that aren't
            // in the list of ids to delete
            Cursor otherArtwork = queryArtwork(MuzeiContract.Artwork.CONTENT_URI,
                    new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID },
                    MuzeiContract.Artwork.COLUMN_NAME_TOKEN + "=? AND " + notInDeleteIds,
                    new String[] { token }, null);
            if (otherArtwork == null) {
                continue;
            }
            if (otherArtwork.getCount() == 0) {
                // There's no non-deleted rows that reference this same artwork URI
                // so we can delete the artwork
                File artwork = getCacheFileForArtworkUri(artworkUri);
                if (artwork != null && artwork.exists()) {
                    artwork.delete();
                }
            }
            otherArtwork.close();
        } else {
            // Check if there are other rows using this same image URI that aren't
            // in the list of ids to delete
            Cursor otherArtwork = queryArtwork(MuzeiContract.Artwork.CONTENT_URI,
                    new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID },
                    MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI + "=? AND " + notInDeleteIds,
                    new String[] { imageUri }, null);
            if (otherArtwork == null) {
                continue;
            }
            if (otherArtwork.getCount() == 0) {
                // There's no non-deleted rows that reference this same artwork URI
                // so we can delete the artwork
                File artwork = getCacheFileForArtworkUri(artworkUri);
                if (artwork != null && artwork.exists()) {
                    artwork.delete();
                }
            }
            otherArtwork.close();
        }
        rowsToDelete.moveToNext();
    }
    rowsToDelete.close();
    int count = db.delete(MuzeiContract.Artwork.TABLE_NAME, finalWhere, selectionArgs);
    if (count > 0) {
        notifyChange(uri);
    }
    return count;
}

From source file:com.openerp.base.res.Res_PartnerSyncHelper.java

public void syncContacts(Context context, Account account) {
    HashMap<String, SyncEntry> localContacts = new HashMap<String, SyncEntry>();
    mContentResolver = context.getContentResolver();
    int company_id = Integer.parseInt(OpenERPAccountManager.currentUser(context).getCompany_id());

    RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true")
            .build();/*from   w ww  . j a  va  2s . c  om*/

    // Load the local contacts
    Uri rawContactUri = RawContacts.CONTENT_URI.buildUpon()
            .appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
            .appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type).build();
    Cursor cursor = mContentResolver.query(rawContactUri, new String[] { BaseColumns._ID, SYNC1_PARTNER_ID },
            null, null, null);

    while (cursor.moveToNext()) {
        SyncEntry entry = new SyncEntry();
        entry.partner_id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        localContacts.put(cursor.getString(1), entry);
    }
    cursor.close();

    try {
        Res_PartnerDBHelper dbHelper = new Res_PartnerDBHelper(context);
        HashMap<String, Object> res = dbHelper.search(dbHelper,
                new String[] { "phone != ? ", "OR", "mobile != ? ", "OR", "email != ?" },
                new String[] { "false", "false", "false" });
        // checking if records exist?
        int total = Integer.parseInt(res.get("total").toString());

        if (total > 0) {
            @SuppressWarnings("unchecked")
            List<HashMap<String, Object>> rows = (List<HashMap<String, Object>>) res.get("records");

            for (HashMap<String, Object> row_data : rows) {

                if (!(row_data.get("company_id").toString()).equalsIgnoreCase("false")) {
                    JSONArray db_company_id = new JSONArray(row_data.get("company_id").toString());
                    String com_id = db_company_id.getJSONArray(0).getString(0).toString();

                    if (com_id.equalsIgnoreCase(String.valueOf(company_id))) {
                        String partnerID = row_data.get("id").toString();
                        String name = (row_data.get("name").toString()).replaceAll("[^\\w\\s]", "");
                        String mail = row_data.get("email").toString();
                        String number = row_data.get("phone").toString();
                        String mobile = row_data.get("mobile").toString();
                        String website = row_data.get("website").toString();
                        String street = row_data.get("street").toString();
                        String street2 = row_data.get("street2").toString();
                        String city = row_data.get("city").toString();
                        String zip = row_data.get("zip").toString();
                        String company = "OpenERP";
                        String image = row_data.get("image_small").toString();
                        if (localContacts.get(row_data.get("id").toString()) == null) {
                            addContact(context, account, partnerID, name, mail, number, mobile, website, street,
                                    street2, city, zip, company, image);
                        }
                    }
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.smedic.tubtub.Pane.java

private Loader suggestionLoader(final List<String> suggestions, final CursorAdapter suggestionAdapter,
        final String query) {
    return getSupportLoaderManager().restartLoader(4, null, new LoaderManager.LoaderCallbacks<List<String>>() {
        @Override/*from w w  w  .jav a  2 s . c  o  m*/
        public Loader<List<String>> onCreateLoader(final int id, final Bundle args) {
            return new SuggestionsLoader(getApplicationContext(), query);
        }

        @Override
        public void onLoadFinished(Loader<List<String>> loader, List<String> data) {
            if (data == null)
                return;
            suggestions.clear();
            suggestions.addAll(data);
            String[] columns = { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1 };
            MatrixCursor cursor = new MatrixCursor(columns);

            for (int i = 0; i < data.size(); i++) {
                String[] tmp = { Integer.toString(i), data.get(i) };
                cursor.addRow(tmp);
            }
            suggestionAdapter.swapCursor(cursor);
        }

        @Override
        public void onLoaderReset(Loader<List<String>> loader) {
            suggestions.clear();
            suggestions.addAll(Collections.<String>emptyList());
        }
    });
}

From source file:com.deliciousdroid.platform.BookmarkManager.java

public static void DeleteBookmark(Bookmark bookmark, Context context) {
    final int id = bookmark.getId();
    String selection = "";

    if (id > 0) {
        selection = BaseColumns._ID + "=" + id;
    } else {//  w  w w  .  j a  v  a 2s .c  o  m
        selection = Bookmark.Url + "='" + bookmark.getUrl() + "'";
    }

    context.getContentResolver().delete(Bookmark.CONTENT_URI, selection, null);
}

From source file:com.amaze.carbonfilemanager.utils.files.Futils.java

private static Uri fileToContentUri(Context context, String path, String volume) {
    String[] projection = null;//  w  w  w  . j a  v a  2s  . c  o  m
    final String where = MediaStore.MediaColumns.DATA + " = ?";
    Uri baseUri = MediaStore.Files.getContentUri(volume);
    boolean isMimeTypeImage = false, isMimeTypeVideo = false, isMimeTypeAudio = false;
    isMimeTypeImage = Icons.isPicture(path);
    if (!isMimeTypeImage) {
        isMimeTypeVideo = Icons.isVideo(path);
        if (!isMimeTypeVideo) {
            isMimeTypeAudio = Icons.isVideo(path);
        }
    }
    if (isMimeTypeImage || isMimeTypeVideo || isMimeTypeAudio) {
        projection = new String[] { BaseColumns._ID };
        if (isMimeTypeImage) {
            baseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if (isMimeTypeVideo) {
            baseUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if (isMimeTypeAudio) {
            baseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }
    } else {
        projection = new String[] { BaseColumns._ID, MediaStore.Files.FileColumns.MEDIA_TYPE };
    }
    ContentResolver cr = context.getContentResolver();
    Cursor c = cr.query(baseUri, projection, where, new String[] { path }, null);
    try {
        if (c != null && c.moveToNext()) {
            boolean isValid = false;
            if (isMimeTypeImage || isMimeTypeVideo || isMimeTypeAudio) {
                isValid = true;
            } else {
                int type = c.getInt(c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MEDIA_TYPE));
                isValid = type != 0;
            }

            if (isValid) {
                // Do not force to use content uri for no media files
                long id = c.getLong(c.getColumnIndexOrThrow(BaseColumns._ID));
                return Uri.withAppendedPath(baseUri, String.valueOf(id));
            }
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return null;
}

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

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader(getActivity(), SipProfile.ACCOUNT_URI,
            new String[] { SipProfile.FIELD_ID + " AS " + BaseColumns._ID, SipProfile.FIELD_ID,
                    SipProfile.FIELD_DISPLAY_NAME, SipProfile.FIELD_WIZARD, SipProfile.FIELD_ACTIVE },
            null, null, null);/*from  w ww  .jav  a 2  s  .  com*/

}

From source file:fr.openbike.android.database.OpenBikeDBAdapter.java

public Cursor getSearchCursor(String query) {
    String table = STATIONS_VIRTUAL_TABLE;
    try {/*  ww w  .  j a va2s .  co  m*/
        Integer.parseInt(query);
        table = "vs." + BaseColumns._ID;
    } catch (NumberFormatException ex) {
    }
    query += "*";

    // TODO: Put network id as argument in rawQuery(), doesn't work
    String s = "SELECT vs._id, ob.availableBikes, ob.freeSlots, ob.isOpen, "
            + "ob.latitude, ob.longitude, ob.name, ob.isFavorite " + "FROM virtual_stations vs "
            + "INNER JOIN stations ob " + "ON (ob._id = vs._id AND vs.network = ob.network) " + "WHERE " + table
            + " match ? AND vs.network = "
            + String.valueOf(mPreferences.getInt(AbstractPreferencesActivity.NETWORK_PREFERENCE,
                    AbstractPreferencesActivity.NO_NETWORK));

    Cursor cursor = mDb.rawQuery(s, new String[] { query });
    return cursor;
}

From source file:li.barter.fragments.ChatDetailsFragment.java

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    if (parent.getId() == R.id.list_chats) {

        final boolean resendOnClick = (Boolean) view.getTag(R.string.tag_resend_on_click);

        if (resendOnClick) {
            final Cursor cursor = (Cursor) mChatDetailAdapter.getItem(position);

            final int dbRowId = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
            final String message = cursor.getString(cursor.getColumnIndex(DatabaseColumns.MESSAGE));

            if (sendChatMessage(message)) {
                //Delete the older message from the table
                DBInterface.deleteAsync(QueryTokens.DELETE_CHAT_MESSAGE, getTaskTag(), null,
                        TableChatMessages.NAME, mMessageSelection, new String[] { String.valueOf(dbRowId) },
                        true, this);
            } else {
                showCrouton(R.string.error_not_connected_to_chat_service, AlertStyle.ERROR);
            }/*www. j  a  va2  s.com*/
        }
    }
}

From source file:com.viktorrudometkin.burramys.fragment.EntriesListFragment.java

public void markAllAsRead() {
    if (mEntriesCursorAdapter != null) {
        Snackbar snackbar = Snackbar//from www. jav a2s.  c  o  m
                .make(getActivity().findViewById(R.id.coordinator_layout), R.string.marked_as_read,
                        Snackbar.LENGTH_LONG)
                .setActionTextColor(ContextCompat.getColor(getActivity(), R.color.light_theme_color_primary))
                .setAction(R.string.undo, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new Thread() {
                            @Override
                            public void run() {
                                if (mJustMarkedAsReadEntries != null && !mJustMarkedAsReadEntries.isClosed()) {
                                    ArrayList<Integer> ids = new ArrayList<>();
                                    while (mJustMarkedAsReadEntries.moveToNext()) {
                                        ids.add(mJustMarkedAsReadEntries.getInt(0));
                                    }
                                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                                    String where = BaseColumns._ID + " IN (" + TextUtils.join(",", ids) + ')';
                                    cr.update(FeedData.EntryColumns.CONTENT_URI,
                                            FeedData.getUnreadContentValues(), where, null);

                                    mJustMarkedAsReadEntries.close();
                                }
                            }
                        }.start();
                    }
                });
        snackbar.getView().setBackgroundResource(R.color.material_grey_900);
        snackbar.show();

        new Thread() {
            @Override
            public void run() {
                ContentResolver cr = MainApplication.getContext().getContentResolver();
                String where = EntryColumns.WHERE_UNREAD + Constants.DB_AND + '(' + EntryColumns.FETCH_DATE
                        + Constants.DB_IS_NULL + Constants.DB_OR + EntryColumns.FETCH_DATE + "<="
                        + mListDisplayDate + ')';
                if (mJustMarkedAsReadEntries != null && !mJustMarkedAsReadEntries.isClosed()) {
                    mJustMarkedAsReadEntries.close();
                }
                mJustMarkedAsReadEntries = cr.query(mCurrentUri, new String[] { BaseColumns._ID }, where, null,
                        null);
                cr.update(mCurrentUri, FeedData.getReadContentValues(), where, null);
            }
        }.start();

        // If we are on "all items" uri, we can remove the notification here
        if (mCurrentUri != null && Constants.NOTIF_MGR != null && (EntryColumns.CONTENT_URI.equals(mCurrentUri)
                || EntryColumns.UNREAD_ENTRIES_CONTENT_URI.equals(mCurrentUri))) {
            Constants.NOTIF_MGR.cancel(0);
        }
    }
}

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

private void printMmsParts(long id) {
    final String[] projection = null;
    String selection = new String("mid=" + id);
    String uriStr = String.format("content://mms/%d/part", id);
    Uri uriAddress = Uri.parse(uriStr);//from   w  ww  .  java 2 s  .  c om
    Cursor c = mResolver.query(uriAddress, projection, selection, null, null);

    if (D)
        Log.d(TAG, "   parts:");
    if (c != null && c.moveToFirst()) {
        do {
            Long partid = c.getLong(c.getColumnIndex(BaseColumns._ID));
            String ct = c.getString(c.getColumnIndex("ct"));
            String name = c.getString(c.getColumnIndex("name"));
            String charset = c.getString(c.getColumnIndex("chset"));
            String filename = c.getString(c.getColumnIndex("fn"));
            String text = c.getString(c.getColumnIndex("text"));
            Integer fd = c.getInt(c.getColumnIndex("_data"));
            String cid = c.getString(c.getColumnIndex("cid"));
            String cl = c.getString(c.getColumnIndex("cl"));
            String cdisp = c.getString(c.getColumnIndex("cd"));

            if (D)
                Log.d(TAG,
                        "     _id : " + partid + "\n     ct : " + ct + "\n     partname : " + name
                                + "\n     charset : " + charset + "\n     filename : " + filename
                                + "\n     text : " + text + "\n     fd : " + fd + "\n     cid : " + cid
                                + "\n     cl : " + cl + "\n     cdisp : " + cdisp);

            /* if (ct.equals("image/jpeg")) { */
            /*     printMmsPartImage(partid); */
            /* } */
        } while (c.moveToNext());
        c.close();
    }
}