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.catnut.plugin.zhihu.ZhihuItemsFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader(getActivity(), CatnutProvider.parse(Zhihu.MULTIPLE), PROJECTION, null, null,
            BaseColumns._ID + " desc limit " + mCount);
}

From source file:io.github.carlorodriguez.alarmon.MediaListView.java

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    setItemChecked(position, true);/*from   ww w .  j a  v a2 s.  c om*/
    cursor.moveToPosition(position);
    selectedName = cursor.getString(cursor.getColumnIndex(nameColumn));
    final int toneIndex = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
    if (toneIndex == DEFAULT_TONE_INDEX) {
        selectedUri = AlarmUtil.getDefaultAlarmUri();
    } else {
        selectedUri = Uri.withAppendedPath(contentUri, "" + toneIndex);
    }
    if (listener != null) {
        listener.onItemPick(selectedUri, selectedName);
    }
}

From source file:com.wheelly.fragments.LocationsListFragment.java

private boolean handleContextItem(int itemId, final long id) {
    switch (itemId) {
    case MENU_RESOLVE:
        startGeocode(new LocationBroker(getActivity()).loadOrCreate(id));
        return true;
    case MENU_EDIT:
        onListItemClick(getListView(), null, 0, id);
        return true;
    case MENU_DELETE:
        getActivity().getContentResolver().delete(Locations.CONTENT_URI, BaseColumns._ID + " = ?",
                new String[] { Long.toString(id) });
        return true;
    case MENU_COLOR:
        new ColorInput(new OnSelectColorListener() {
            @Override//from   w  ww  .  j  a v  a2 s.  c o  m
            public void onSelect(DialogInterface dialog, int which, int color, String argb) {
                final LocationBroker broker = new LocationBroker(getActivity());
                final ContentValues location = broker.loadOrCreate(id);

                if (location.size() > 0) {
                    location.put("color", argb);
                    broker.updateOrInsert(location);
                }
            }
        }).show(getFragmentManager(), null);
        return true;
    }
    ;
    return false;
}

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

/**
 * Creates and initializes a column project for all columns for Sources
 *
 * @return The all column projection map for Sources
 *//*ww  w.j av  a  2s .  com*/
private static HashMap<String, String> buildAllSourcesColumnProjectionMap() {
    final HashMap<String, String> allColumnProjectionMap = new HashMap<>();
    allColumnProjectionMap.put(BaseColumns._ID, BaseColumns._ID);
    allColumnProjectionMap.put(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME,
            MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME);
    allColumnProjectionMap.put(MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED,
            MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED);
    allColumnProjectionMap.put(MuzeiContract.Sources.COLUMN_NAME_DESCRIPTION,
            MuzeiContract.Sources.COLUMN_NAME_DESCRIPTION);
    allColumnProjectionMap.put(MuzeiContract.Sources.COLUMN_NAME_WANTS_NETWORK_AVAILABLE,
            MuzeiContract.Sources.COLUMN_NAME_WANTS_NETWORK_AVAILABLE);
    allColumnProjectionMap.put(MuzeiContract.Sources.COLUMN_NAME_SUPPORTS_NEXT_ARTWORK_COMMAND,
            MuzeiContract.Sources.COLUMN_NAME_SUPPORTS_NEXT_ARTWORK_COMMAND);
    allColumnProjectionMap.put(MuzeiContract.Sources.COLUMN_NAME_COMMANDS,
            MuzeiContract.Sources.COLUMN_NAME_COMMANDS);
    return allColumnProjectionMap;
}

From source file:org.opensilk.music.library.mediastore.util.FilesUtil.java

@NonNull
public static List<Track> convertAudioFilesToTracks(Context context, File base, List<File> audioFiles) {
    if (audioFiles.size() == 0) {
        return Collections.emptyList();
    }//w  w w  . ja va 2 s.  c  om

    final List<Track> trackList = new ArrayList<>(audioFiles.size());

    Cursor c = null;
    try {
        final HashMap<String, File> pathMap = new HashMap<>();

        //Build the selection
        final int size = audioFiles.size();
        final StringBuilder selection = new StringBuilder();
        selection.append(MediaStore.Audio.AudioColumns.DATA + " IN (");
        for (int i = 0; i < size; i++) {
            final File f = audioFiles.get(i);
            final String path = f.getAbsolutePath();
            pathMap.put(path, f); //Add file to map while where iterating
            //TODO it would probably be better to use selectionArgs
            selection.append("'").append(StringUtils.replace(path, "'", "''")).append("'");
            if (i < size - 1) {
                selection.append(",");
            }
        }
        selection.append(")");

        //make query
        c = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                Projections.SONG_FILE, selection.toString(), null, null);
        if (c != null && c.moveToFirst()) {
            do {
                final File f = pathMap
                        .remove(c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA)));
                if (f != null) {
                    try {
                        Track.Builder tb = Track.builder()
                                .setIdentity(c.getString(c.getColumnIndexOrThrow(BaseColumns._ID)))
                                .setName(getStringOrNull(c, MediaStore.Audio.AudioColumns.DISPLAY_NAME))
                                .setArtistName(getStringOrNull(c, MediaStore.Audio.AudioColumns.ARTIST))
                                .setAlbumName(getStringOrNull(c, MediaStore.Audio.AudioColumns.ALBUM))
                                .setAlbumArtistName(getStringOrNull(c, "album_artist"))
                                .setAlbumIdentity(getStringOrNull(c, MediaStore.Audio.AudioColumns.ALBUM_ID))
                                .setDuration(
                                        (int) (getLongOrZero(c, MediaStore.Audio.AudioColumns.DURATION) / 1000))
                                .setMimeType(getStringOrNull(c, MediaStore.Audio.AudioColumns.MIME_TYPE))
                                .setDataUri(
                                        generateDataUri(c.getString(c.getColumnIndexOrThrow(BaseColumns._ID))))
                                .setArtworkUri(generateArtworkUri(
                                        c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID))));
                        trackList.add(tb.build());
                    } catch (IllegalArgumentException ignored) {
                    }
                }
            } while (c.moveToNext());
        }
        if (!pathMap.isEmpty()) {
            Timber.w("%d audioFiles didn't make the cursor", pathMap.size());
            for (File f : pathMap.values()) {
                trackList.add(makeTrackFromFile(base, f));
            }
        }
    } catch (Exception e) {
        if (DUMPSTACKS)
            Timber.e(e, "convertAudioFilesToTracks");
    } finally {
        closeQuietly(c);
    }
    return trackList;
}

From source file:com.bt.download.android.gui.Librarian.java

public String renameFile(FileDescriptor fd, String newFileName) {
    try {//from w  w w.  j av  a2 s .  co  m

        String filePath = fd.filePath;

        File oldFile = new File(filePath);

        String ext = FilenameUtils.getExtension(filePath);

        File newFile = new File(oldFile.getParentFile(), newFileName + '.' + ext);

        ContentResolver cr = context.getContentResolver();

        ContentValues values = new ContentValues();

        values.put(MediaColumns.DATA, newFile.getAbsolutePath());
        values.put(MediaColumns.DISPLAY_NAME, FilenameUtils.getBaseName(newFileName));
        values.put(MediaColumns.TITLE, FilenameUtils.getBaseName(newFileName));

        TableFetcher fetcher = TableFetchers.getFetcher(fd.fileType);

        cr.update(fetcher.getContentUri(), values, BaseColumns._ID + "=?",
                new String[] { String.valueOf(fd.id) });

        oldFile.renameTo(newFile);

        return newFile.getAbsolutePath();

    } catch (Throwable e) {
        Log.e(TAG, "Failed to rename file: " + fd, e);
    }

    return null;
}

From source file:pl.selvin.android.listsyncsample.ui.EditItemActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
    case R.id.ui_edit_cancel:
        finish();//  ww  w  .j a v  a2  s.  c  o m
        return true;
    case R.id.ui_edit_save:
        String name = edName.getText().toString(), desc = edDesc.getText().toString();
        if (name.length() != 0 && desc.length() != 0) {
            ContentValues values = new ContentValues();
            values.put(Database.Item.NAME, name);
            values.put(Database.Item.DESCRIPTION, desc);
            Cursor c = (Cursor) sPriority.getSelectedItem();
            values.put(Database.Item.PRIORITY, c.getInt(c.getColumnIndex(BaseColumns._ID)));
            c = (Cursor) sStatus.getSelectedItem();
            values.put(Database.Item.STATUS, c.getInt(c.getColumnIndex(BaseColumns._ID)));
            Calendar cal = (Calendar) tStartDate.getTag();
            values.put(Database.Item.STARTDATE, sdf.format(cal.getTime()));
            cal = (Calendar) tEndDate.getTag();
            values.put(Database.Item.ENDDATE, sdf.format(cal.getTime()));
            if (id == null) {
                values.put(Database.Item.ID, UUID.randomUUID().toString());
                values.put(Database.Item.LISTID, listID);
                values.put(Database.Item.USERID, UserID);
                getContentResolver().insert(ListProvider.getHelper().getDirUri(Database.Item.TABLE_NAME),
                        values);
            } else {
                getContentResolver().update(id, values, null, null);
            }
            finish();
        } else {
            Toast.makeText(this, getResources().getString(R.string.ui_name_description_empty),
                    Toast.LENGTH_SHORT).show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:de.jdellay.wallet.ExchangeRatesProvider.java

@Override
public Cursor query(final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    final long now = System.currentTimeMillis();
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
    int provider = Integer.parseInt(sp.getString(Configuration.PREFS_KEY_EXCHANGE_PROVIDER, "0"));
    boolean forceRefresh = sp.getBoolean(Configuration.PREFS_KEY_EXCHANGE_FORCE_REFRESH, false);
    if (forceRefresh)
        sp.edit().putBoolean(Configuration.PREFS_KEY_EXCHANGE_FORCE_REFRESH, false).commit();

    if (lastUpdated == 0 || now - lastUpdated > UPDATE_FREQ_MS) {
        float newCcnBtcConversion = -1;
        if ((ccnBtcConversion == -1 && newCcnBtcConversion == -1) || forceRefresh)
            newCcnBtcConversion = requestCcnBtcConversion(provider);

        if (newCcnBtcConversion != -1)
            ccnBtcConversion = newCcnBtcConversion;

        if (CCNBtcConversion == -1)
            return null;

        Map<String, ExchangeRate> newExchangeRates = null;
        if (newExchangeRates == null)
            newExchangeRates = requestExchangeRates(BITCOINAVERAGE_URL, ccnBtcConversion, userAgent,
                    BITCOINAVERAGE_SOURCE, BITCOINAVERAGE_FIELDS);
        if (newExchangeRates == null)
            newExchangeRates = requestExchangeRates(BLOCKCHAININFO_URL, ccnBtcConversion, userAgent,
                    BLOCKCHAININFO_SOURCE, BLOCKCHAININFO_FIELDS);

        if (newExchangeRates != null) {
            String providerUrl;/* w w  w .j a va 2  s .co  m*/
            switch (provider) {
            case 0:
                providerUrl = "http://www.cryptsy.com";
                break;
            case 1:
                providerUrl = "http://www.vircurex.com";
                break;
            default:
                providerUrl = "";
                break;
            }
            float mBTCRate = ccnBtcConversion * 1000;
            String strmBTCRate = String.format(Locale.US, "%.5f", mBTCRate).replace(',', '.');
            newExchangeRates.put("mBTC", new ExchangeRate("mBTC",
                    new BigDecimal(GenericUtils.toNanoCoins(strmBTCRate, 0)).toBigInteger(), providerUrl));
            newExchangeRates.put("CCN",
                    new ExchangeRate("CCN", BigInteger.valueOf(100000000), "priceofccn.com"));
            exchangeRates = newExchangeRates;
            lastUpdated = now;

            final ExchangeRate exchangeRateToCache = bestExchangeRate(config.getExchangeCurrencyCode());
            if (exchangeRateToCache != null)
                config.setCachedExchangeRate(exchangeRateToCache);
        }
    }

    if (exchangeRates == null || ccnBtcConversion == -1)
        return null;

    final MatrixCursor cursor = new MatrixCursor(
            new String[] { BaseColumns._ID, KEY_CURRENCY_CODE, KEY_RATE, KEY_SOURCE });

    if (selection == null) {
        for (final Map.Entry<String, ExchangeRate> entry : exchangeRates.entrySet()) {
            final ExchangeRate rate = entry.getValue();
            cursor.newRow().add(rate.currencyCode.hashCode()).add(rate.currencyCode).add(rate.rate.longValue())
                    .add(rate.source);
        }
    } else if (selection.equals(KEY_CURRENCY_CODE)) {
        final ExchangeRate rate = bestExchangeRate(selectionArgs[0]);
        if (rate != null)
            cursor.newRow().add(rate.currencyCode.hashCode()).add(rate.currencyCode).add(rate.rate.longValue())
                    .add(rate.source);
    }

    return cursor;
}

From source file:org.catnut.fragment.FavoriteFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String selection = mSelection;
    boolean search = args.getBoolean(SEARCH_TWEET);
    if (search) {
        if (!TextUtils.isEmpty(mCurFilter)) {
            selection = new StringBuilder(mSelection).append(" and ").append(Status.columnText).append(" like ")
                    .append(CatnutUtils.like(mCurFilter)).toString();
        } else {//from   w  ww  .ja va  2  s. c o m
            search = false;
        }
    }
    int limit = args.getInt(TAG, getFetchSize());
    return CatnutUtils.getCursorLoader(getActivity(), CatnutProvider.parse(Status.MULTIPLE), PROJECTION,
            selection, null, Status.TABLE + " as s", "inner join " + User.TABLE + " as u on s.uid=u._id",
            "s." + BaseColumns._ID + " desc", search ? null : String.valueOf(limit));
}

From source file:com.wheelly.fragments.LocationsMapFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    BusProvider.getInstance().register(this);

    inSelectMode = getActivity().getIntent().hasExtra(LocationActivity.LOCATION_ID_EXTRA);

    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());

    // Showing status
    if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
        dialog.show();//w ww.j a  va 2  s .co  m

    } else { // Google Play Services are available

        // Getting GoogleMap object from the fragment
        googleMap = getMap();
    }

    ApiAdapterFactory.getApiAdapter().configureMapViewContextualMenu(this, new MapContextActionCallback() {
        private EditText editText;

        @Override
        public void onPrepare(Menu menu, Marker marker) {
            configureTitleWidget(marker);
        }

        @SuppressLint("NewApi")
        @Override
        public void onCreate(Menu menu) {
            editText = (EditText) menu.add(0, 0, 0, "name").setIcon(android.R.drawable.ic_menu_edit)
                    .setActionView(R.layout.location_edit).getActionView().findViewById(R.id.location_name);

            menu.add(0, 1, 0, R.string.item_add).setIcon(android.R.drawable.ic_menu_save);
        }

        private void configureTitleWidget(Marker marker) {
            if (null != marker && null != editText) {
                try {
                    final long id = Long.parseLong(marker.getSnippet());
                    editText.setText(new LocationBroker(getActivity()).loadOrCreate(id).getAsString("name"));
                } catch (NumberFormatException nfex) {
                    LocationUtils.resolveAddress(getActivity(), marker.getPosition(), "",
                            new AddressResolveCallback() {
                                @Override
                                public void onResolved(Address address) {
                                    if (getResources().getString(R.string.new_location)
                                            .equals(editText.getText().toString()) && null != address) {
                                        editText.setText(LocationUtils.formatAddress(address));
                                    }
                                }
                            });
                }
            }
        }

        @Override
        public boolean onClick(MenuItem item, Marker marker) {
            if (null != marker) {
                final ContentValues myLocation = new ContentValues();

                try {
                    final long id = Long.parseLong(marker.getSnippet());
                    myLocation.put(BaseColumns._ID, id);
                } catch (NumberFormatException nfex) {
                    myLocation.put("provider", "fusion");
                }

                if (null != editText) {
                    myLocation.put("name", editText.getText().toString());
                }

                myLocation.put("latitude", marker.getPosition().latitude);
                myLocation.put("longitude", marker.getPosition().longitude);
                myLocation.put("datetime", System.currentTimeMillis());

                LocationUtils.resolveAddress(getActivity(), marker.getPosition(),
                        myLocation.getAsString("name"), new AddressResolveCallback() {
                            @Override
                            public void onResolved(Address address) {
                                if (null != address) {
                                    myLocation.put("resolved_address", LocationUtils.formatAddress(address));
                                }

                                new LocationBroker(getActivity()).updateOrInsert(myLocation);
                            }
                        });

                return true;
            }
            return false;
        }
    });
}