下面列出了android.provider.BaseColumns#_ID 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public synchronized void removeDeletedRawContacts(@NonNull Account account) {
Uri currentContactsUri = RawContacts.CONTENT_URI.buildUpon()
.appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
.appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type)
.appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true")
.build();
String[] projection = new String[] {BaseColumns._ID, RawContacts.SYNC1};
try (Cursor cursor = context.getContentResolver().query(currentContactsUri, projection, RawContacts.DELETED + " = ?", new String[] {"1"}, null)) {
while (cursor != null && cursor.moveToNext()) {
long rawContactId = cursor.getLong(0);
Log.i(TAG, "Deleting raw contact: " + cursor.getString(1) + ", " + rawContactId);
context.getContentResolver().delete(currentContactsUri, RawContacts._ID + " = ?", new String[] {String.valueOf(rawContactId)});
}
}
}
private Cursor getCursorForPhone(String phone) {
if (phone.isEmpty())
return null;
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
String[] projection = new String[]{BaseColumns._ID};
ArrayList<String> contactIds = new ArrayList<>();
Cursor phoneCursor = contentResolver.query(uri, projection, null, null, null);
while (phoneCursor != null && phoneCursor.moveToNext()){
contactIds.add(phoneCursor.getString(phoneCursor.getColumnIndex(BaseColumns._ID)));
}
if (phoneCursor!= null)
phoneCursor.close();
if (!contactIds.isEmpty()) {
String contactIdsListString = contactIds.toString().replace("[", "(").replace("]", ")");
String contactSelection = ContactsContract.Data.CONTACT_ID + " IN " + contactIdsListString;
return contentResolver.query(ContactsContract.Data.CONTENT_URI, PROJECTION, contactSelection, null, null);
}
return null;
}
private Cursor getCursorForPhone(String phone) {
if (phone.isEmpty())
return null;
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
String[] projection = new String[]{BaseColumns._ID};
ArrayList<String> contactIds = new ArrayList<>();
Cursor phoneCursor = contentResolver.query(uri, projection, null, null, null);
while (phoneCursor != null && phoneCursor.moveToNext()){
contactIds.add(phoneCursor.getString(phoneCursor.getColumnIndex(BaseColumns._ID)));
}
if (phoneCursor!= null)
phoneCursor.close();
if (!contactIds.isEmpty()) {
String contactIdsListString = contactIds.toString().replace("[", "(").replace("]", ")");
String contactSelection = ContactsContract.Data.CONTACT_ID + " IN " + contactIdsListString;
return contentResolver.query(ContactsContract.Data.CONTENT_URI, PROJECTION, contactSelection, null, null);
}
return null;
}
/**
* Creates a cursor that contains contacts group corresponding to an sip
* account.
*/
private Cursor createContentCursorFor(SipProfile account) {
Cursor c = null;
if(!TextUtils.isEmpty(account.android_group)) {
c = ContactsWrapper.getInstance().getContactsByGroup(getContext(), account.android_group);
}
if(c != null) {
return c;
}
MatrixCursor mc = new MatrixCursor (new String[] {
BaseColumns._ID,
ContactsWrapper.FIELD_TYPE
});
mc.addRow(new Object[] {account.id, ContactsWrapper.TYPE_CONFIGURE});
return mc;
}
private @NonNull Map<String, SignalContact> getSignalRawContacts(@NonNull Account account) {
Uri currentContactsUri = RawContacts.CONTENT_URI.buildUpon()
.appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
.appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type).build();
Map<String, SignalContact> signalContacts = new HashMap<>();
Cursor cursor = null;
try {
String[] projection = new String[] {BaseColumns._ID, RawContacts.SYNC1, RawContacts.SYNC4, RawContacts.CONTACT_ID, RawContacts.DISPLAY_NAME_PRIMARY, RawContacts.DISPLAY_NAME_SOURCE};
cursor = context.getContentResolver().query(currentContactsUri, projection, null, null, null);
while (cursor != null && cursor.moveToNext()) {
String currentAddress = PhoneNumberFormatter.get(context).format(cursor.getString(1));
long rawContactId = cursor.getLong(0);
long contactId = cursor.getLong(3);
String supportsVoice = cursor.getString(2);
String rawContactDisplayName = cursor.getString(4);
String aggregateDisplayName = getDisplayName(contactId);
int rawContactDisplayNameSource = cursor.getInt(5);
signalContacts.put(currentAddress, new SignalContact(rawContactId, supportsVoice, rawContactDisplayName, aggregateDisplayName, rawContactDisplayNameSource));
}
} finally {
if (cursor != null)
cursor.close();
}
return signalContacts;
}
private void populateSuggestionsAdapter(String query) {
final MatrixCursor c = new MatrixCursor(new String[]{BaseColumns._ID, "suggestion"});
List<String> suggestionsForQuery = getSuggestionsForQuery(query);
for (int i = 0, suggestionsForQuerySize = suggestionsForQuery.size(); i < suggestionsForQuerySize; i++) {
String suggestion = suggestionsForQuery.get(i);
c.addRow(new Object[]{i, suggestion});
}
mSearchSuggestionsAdapter.changeCursor(c);
}
@Nullable
private static SortedLongCursor makeSortedCursor(@NonNull final Context context, @Nullable final Cursor cursor, final int idColumn) {
if (cursor != null && cursor.moveToFirst()) {
// create the list of ids to select against
StringBuilder selection = new StringBuilder();
selection.append(BaseColumns._ID);
selection.append(" IN (");
// this songs the order of the ids
long[] order = new long[cursor.getCount()];
long id = cursor.getLong(idColumn);
selection.append(id);
order[cursor.getPosition()] = id;
while (cursor.moveToNext()) {
selection.append(",");
id = cursor.getLong(idColumn);
order[cursor.getPosition()] = id;
selection.append(String.valueOf(id));
}
selection.append(")");
// get a list of songs with the data given the selection statement
Cursor songCursor = SongLoader.makeSongCursor(context, selection.toString(), null);
if (songCursor != null) {
// now return the wrapped TopSongsCursor to handle sorting given order
return new SortedLongCursor(songCursor, order, BaseColumns._ID);
}
}
return null;
}
@Nullable
private static SortedLongCursor makeSortedCursor(@NonNull final Context context, @Nullable final Cursor cursor, final int idColumn) {
if (cursor != null && cursor.moveToFirst()) {
// create the list of ids to select against
StringBuilder selection = new StringBuilder();
selection.append(BaseColumns._ID);
selection.append(" IN (");
// this tracks the order of the ids
long[] order = new long[cursor.getCount()];
long id = cursor.getLong(idColumn);
selection.append(id);
order[cursor.getPosition()] = id;
while (cursor.moveToNext()) {
selection.append(",");
id = cursor.getLong(idColumn);
order[cursor.getPosition()] = id;
selection.append(String.valueOf(id));
}
selection.append(")");
// get a list of songs with the data given the selection statement
Cursor songCursor = SongLoader.makeSongCursor(context, selection.toString(), null);
if (songCursor != null) {
// now return the wrapped TopTracksCursor to handle sorting given order
return new SortedLongCursor(songCursor, order, BaseColumns._ID);
}
}
return null;
}
@Override
protected ArrayList<Playlist> doInBackground(Void... params) {
try {
String[] columns = {
BaseColumns._ID,
MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME,
MediaStore.Audio.Playlists.DATA
};
mCursor = mContext.getContentResolver().query(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
columns,
null,
null,
MediaStore.Audio.Playlists.DEFAULT_SORT_ORDER);
addDefaultPlayLists();
if (mCursor != null && mCursor.moveToFirst()) {
do {
Playlist song = new Playlist(mCursor.getLong(1),mCursor.getString(2));
mPlayList.add(song);
} while (mCursor.moveToNext());
}
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
} catch (Exception e) {
e.printStackTrace();
}
return mPlayList;
}
@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);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), SipManager.FILTER_URI, new String[] {
BaseColumns._ID,
Filter.FIELD_ACCOUNT,
Filter.FIELD_ACTION,
Filter.FIELD_MATCHES,
Filter.FIELD_PRIORITY,
Filter.FIELD_REPLACE
}, Filter.FIELD_ACCOUNT + "=?", new String[] {Long.toString(accountId)}, Filter.DEFAULT_ORDER);
}
/**
* Creates a cursor that contains a single row and maps the section to the
* given value.
*/
private Cursor createHeaderCursorFor(SipProfile account) {
MatrixCursor matrixCursor =
new MatrixCursor(new String[] {
BaseColumns._ID,
ContactsWrapper.FIELD_TYPE,
SipProfile.FIELD_DISPLAY_NAME,
SipProfile.FIELD_WIZARD,
SipProfile.FIELD_ANDROID_GROUP,
SipProfile.FIELD_PUBLISH_ENABLED,
SipProfile.FIELD_REG_URI,
SipProfile.FIELD_PROXY,
SipProfile.FIELD_ACC_ID
});
String proxies = "";
if(account.proxies != null) {
proxies = TextUtils.join(SipProfile.PROXIES_SEPARATOR, account.proxies);
}
matrixCursor.addRow(new Object[] {
account.id,
ContactsWrapper.TYPE_GROUP,
account.display_name,
account.wizard,
account.android_group,
account.publish_enabled,
account.reg_uri,
proxies,
account.acc_id
});
return matrixCursor;
}
@Nullable
private static SortedLongCursor makeSortedCursor(@NonNull final Context context, @Nullable final Cursor cursor, final int idColumn) {
if (cursor != null && cursor.moveToFirst()) {
// create the list of ids to select against
StringBuilder selection = new StringBuilder();
selection.append(BaseColumns._ID);
selection.append(" IN (");
// this tracks the order of the ids
long[] order = new long[cursor.getCount()];
long id = cursor.getLong(idColumn);
selection.append(id);
order[cursor.getPosition()] = id;
while (cursor.moveToNext()) {
selection.append(",");
id = cursor.getLong(idColumn);
order[cursor.getPosition()] = id;
selection.append(String.valueOf(id));
}
selection.append(")");
// get a list of songs with the data given the selection statement
Cursor songCursor = SongLoader.makeSongCursor(context, selection.toString(), null);
if (songCursor != null) {
// now return the wrapped TopTracksCursor to handle sorting given order
return new SortedLongCursor(songCursor, order, BaseColumns._ID);
}
}
return null;
}
private void populateSuggestionsAdapter(String query) {
final MatrixCursor c = new MatrixCursor(new String[]{BaseColumns._ID, "suggestion"});
List<String> suggestionsForQuery = getSuggestionsForQuery(query);
for (int i = 0, suggestionsForQuerySize = suggestionsForQuery.size(); i < suggestionsForQuerySize; i++) {
String suggestion = suggestionsForQuery.get(i);
c.addRow(new Object[]{i, suggestion});
}
mSearchSuggestionsAdapter.changeCursor(c);
}
private Song getSongs(String[] whereArgs) {
Song song = null;
String[] columns = {
BaseColumns._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.TRACK,
MediaStore.Audio.Media.DURATION
};
Cursor cursor = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
columns,
MediaStore.Audio.Media.DATA + " LIKE ?", whereArgs, MediaStore.Audio.Media.TITLE);
if (cursor != null && cursor.moveToFirst()) {
do {
song = new Song(
cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getLong(3),
cursor.getString(4),
cursor.getLong(5),
cursor.getString(6),
cursor.getInt(7),
cursor.getLong(8));
} while (cursor.moveToNext());
}
return song;
}
@Nullable
private static SortedLongCursor makeSortedCursor(@NonNull final Context context, @Nullable final Cursor cursor, final int idColumn) {
if (cursor != null && cursor.moveToFirst()) {
// create the list of ids to select against
StringBuilder selection = new StringBuilder();
selection.append(BaseColumns._ID);
selection.append(" IN (");
// this tracks the order of the ids
long[] order = new long[cursor.getCount()];
long id = cursor.getLong(idColumn);
selection.append(id);
order[cursor.getPosition()] = id;
while (cursor.moveToNext()) {
selection.append(",");
id = cursor.getLong(idColumn);
order[cursor.getPosition()] = id;
selection.append(String.valueOf(id));
}
selection.append(")");
// get a list of songs with the data given the selection statement
Cursor songCursor = SongLoader.makeSongCursor(context, selection.toString(), null);
if (songCursor != null) {
// now return the wrapped TopTracksCursor to handle sorting given order
return new SortedLongCursor(songCursor, order, BaseColumns._ID);
}
}
return null;
}
@Query("select id as "+ BaseColumns._ID +", `query` as "+ SearchManager.SUGGEST_COLUMN_TEXT_1+","+ R.drawable.ic_restore_24dp +" as "+SearchManager.SUGGEST_COLUMN_ICON_1+",`query` as "+SearchManager.SUGGEST_COLUMN_QUERY+" from search_suggestion where `query` like :needle and `query` is not :actual order by id desc limit 30")
abstract Cursor getSearchSuggestions(String needle, String actual);
private static Uri fileToContentUri(Context context, String path, String volume) {
String[] projection = null;
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;
}
/**
* Returns a {@link ContentWriter} which can be used to update the current item.
*/
public ContentWriter updater() {
return new ContentWriter(mContext, new ContentWriter.CommitParams(
BaseColumns._ID + "= ?", new String[]{Long.toString(id)}));
}
public static ArrayList<Song> getTracksForSelection(String from, String selectionCondition) {
Common mApp = (Common) Common.getInstance();
String[] columns = {
BaseColumns._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.TRACK,
MediaStore.Audio.Media.ARTIST_ID,
};
String selection = null;
Uri uri = null;
String selectionArgs[] = null;
String sortBy = null;
if (from.equalsIgnoreCase("ALBUMS")) {
selection = "is_music=1 AND title != '' AND " + MediaStore.Audio.Media.ALBUM_ID + "=?";
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
selectionArgs = new String[]{selectionCondition};
sortBy = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
} else if (from.equalsIgnoreCase("ARTIST")) {
selection = "is_music=1 AND title != '' AND " + MediaStore.Audio.Media.ARTIST_ID + "=?";
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
selectionArgs = new String[]{selectionCondition};
sortBy = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
} else if (from.equalsIgnoreCase("GENRES")) {
uri = MediaStore.Audio.Genres.Members.getContentUri("external", Long.parseLong(selectionCondition));
sortBy = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
} else if (from.equalsIgnoreCase("PLAYLISTS")) {
if (selectionCondition.equalsIgnoreCase("-1")) {
int x = PreferencesHelper.getInstance().getInt(PreferencesHelper.Key.RECENTLY_ADDED_WEEKS, 1) * (3600 * 24 * 7);
selection = MediaStore.MediaColumns.DATE_ADDED + ">" + (System.currentTimeMillis() / 1000 - x) + " AND is_music=1";
sortBy = MediaStore.Audio.Media.DATE_ADDED + " DESC";
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
} else if (selectionCondition.equalsIgnoreCase("-2")) {
return mApp.getDBAccessHelper().getFavorites();
} else if (selectionCondition.equalsIgnoreCase("-3")) {
return mApp.getDBAccessHelper().getTopTracks();
} else if (selectionCondition.equalsIgnoreCase("-4")) {
return mApp.getDBAccessHelper().getRecentlyPlayed();
} else {
columns[0] = MediaStore.Audio.Playlists.Members.AUDIO_ID;
uri = MediaStore.Audio.Playlists.Members.getContentUri("external", Long.parseLong(selectionCondition));
}
} else if (from.equalsIgnoreCase("SONGS")) {
selection = "is_music=1 AND title != ''";
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
sortBy = PreferencesHelper.getInstance().getString(PreferencesHelper.Key.SONG_SORT_ORDER, MediaStore.Audio.Media.DEFAULT_SORT_ORDER) +
PreferencesHelper.getInstance().getString(PreferencesHelper.Key.SONG_SORT_TYPE, " ASC");
}
ArrayList<Song> songs = new ArrayList<>();
Cursor cursor = Common.getInstance().getContentResolver().query(
uri,
columns,
selection,
selectionArgs,
sortBy);
int audioIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
if (!selectionCondition.equalsIgnoreCase("-1") && from.equalsIgnoreCase("PLAYLISTS")) {
audioIndex = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID);
}
if (cursor != null && cursor.moveToFirst()) {
do {
Song song = new Song(
cursor.getLong(audioIndex),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)),
cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)),
cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.TRACK)),
cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))
);
songs.add(song);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return songs;
}