下面列出了怎么用android.provider.BaseColumns的API类实例代码及写法,或者点击链接到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)});
}
}
}
public static NetworkConnection fromConnectionId(Context context, int id) {
Cursor cursor = null;
NetworkConnection networkConnection = null;
try {
cursor = context.getContentResolver()
.query(ExplorerProvider.buildConnection(), null,
BaseColumns._ID + "=? "
, new String[]{Integer.toString(id)}, null);
if (null != cursor && cursor.moveToFirst()) {
networkConnection = NetworkConnection.fromConnectionsCursor(cursor);
}
} catch (Exception e) {
Log.w(TAG, "Failed to load some roots from " + NetworkStorageProvider.AUTHORITY + ": " + e);
Crashlytics.logException(e);
} finally {
IoUtils.closeQuietly(cursor);
}
return networkConnection;
}
/**
* Get an Uri from an file path.
*
* @param path The file path.
* @return The Uri.
*/
private static Uri getUriFromFile(Context context, final String path) {
ContentResolver resolver = context.getContentResolver();
Cursor filecursor = resolver.query(MediaStore.Files.getContentUri("external"),
new String[]{BaseColumns._ID}, MediaStore.MediaColumns.DATA + " = ?",
new String[]{path}, MediaStore.MediaColumns.DATE_ADDED + " desc");
if (filecursor == null) {
return null;
}
filecursor.moveToFirst();
if (filecursor.isAfterLast()) {
filecursor.close();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, path);
return resolver.insert(MediaStore.Files.getContentUri("external"), values);
} else {
int imageId = filecursor.getInt(filecursor.getColumnIndex(BaseColumns._ID));
Uri uri = MediaStore.Files.getContentUri("external").buildUpon().appendPath(
Integer.toString(imageId)).build();
filecursor.close();
return uri;
}
}
/**
* Given the recipients list and subject of an unsaved message,
* return its thread ID. If the message starts a new thread,
* allocate a new thread ID. Otherwise, use the appropriate
* existing thread ID.
*
* <p>Find the thread ID of the same set of recipients (in any order,
* without any additions). If one is found, return it. Otherwise,
* return a unique thread ID.</p>
*/
private static long getOrCreateThreadIdInternal(Context context, Set<String> recipients) {
Uri.Builder uriBuilder = THREAD_ID_CONTENT_URI.buildUpon();
for (String recipient : recipients) {
uriBuilder.appendQueryParameter("recipient", recipient);
}
Uri uri = uriBuilder.build();
Cursor cursor = query(
context.getContentResolver(), uri, new String[] {BaseColumns._ID});
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return cursor.getLong(0);
}
} finally {
cursor.close();
}
}
throw new IllegalArgumentException("Unable to find or allocate a thread ID.");
}
public static Uri getUriFromFile(final String path, Context context) {
ContentResolver resolver = context.getContentResolver();
Cursor filecursor = resolver.query(MediaStore.Files.getContentUri("external"),
new String[]{BaseColumns._ID}, MediaStore.MediaColumns.DATA + " = ?",
new String[]{path}, MediaStore.MediaColumns.DATE_ADDED + " desc");
filecursor.moveToFirst();
if (filecursor.isAfterLast()) {
filecursor.close();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, path);
return resolver.insert(MediaStore.Files.getContentUri("external"), values);
} else {
int imageId = filecursor.getInt(filecursor.getColumnIndex(BaseColumns._ID));
Uri uri = MediaStore.Files.getContentUri("external").buildUpon().appendPath(
Integer.toString(imageId)).build();
filecursor.close();
return uri;
}
}
/**
* Get an Uri from an file path.
*
* @param path The file path.
* @return The Uri.
*/
public static Uri getUriFromFile(final String path, final Context c) {
ContentResolver resolver = c.getContentResolver();
Cursor filecursor = resolver.query(MediaStore.Files.getContentUri("external"),
new String[] {BaseColumns._ID}, MediaColumns.DATA + " = ?",
new String[] {path}, MediaColumns.DATE_ADDED + " desc");
if (filecursor == null) {
return null;
}
filecursor.moveToFirst();
if (filecursor.isAfterLast()) {
filecursor.close();
ContentValues values = new ContentValues();
values.put(MediaColumns.DATA, path);
return resolver.insert(MediaStore.Files.getContentUri("external"), values);
}
else {
int imageId = filecursor.getInt(filecursor.getColumnIndex(BaseColumns._ID));
Uri uri = MediaStore.Files.getContentUri("external").buildUpon().appendPath(
Integer.toString(imageId)).build();
filecursor.close();
return uri;
}
}
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;
}
public static String getNameForPlaylist(@NonNull final Context context, final long id) {
try {
Cursor cursor = context.getContentResolver().query(EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.PlaylistsColumns.NAME},
BaseColumns._ID + "=?",
new String[]{String.valueOf(id)},
null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return cursor.getString(0);
}
} finally {
cursor.close();
}
}
} catch (SecurityException ignored) {
}
return "";
}
public DownloadTask loadTask(String taskId) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String whereClause = TaskContract.TaskEntry.COLUMN_NAME_TASK_ID + " = ?";
String[] whereArgs = new String[]{taskId};
Cursor cursor = db.query(
TaskContract.TaskEntry.TABLE_NAME,
projection,
whereClause,
whereArgs,
null,
null,
BaseColumns._ID + " DESC",
"1"
);
DownloadTask result = null;
while (cursor.moveToNext()) {
result = parseCursor(cursor);
}
cursor.close();
return result;
}
public boolean onPopupMenuItemClick(MenuItem item, int position) {
final Cursor cursor = mAdapter.getItem(position);
int connection_id = getCursorInt(cursor, BaseColumns._ID);
NetworkConnection networkConnection = NetworkConnection.fromConnectionsCursor(cursor);
final int id = item.getItemId();
switch (id) {
case R.id.menu_edit:
editConnection(connection_id);
return true;
case R.id.menu_delete:
if(!networkConnection.type.equals(SERVER)) {
deleteConnection(connection_id);
} else {
((BaseActivity)getActivity())
.showSnackBar("Default server connection can't be deleted",
Snackbar.LENGTH_SHORT);
}
return true;
default:
return false;
}
}
private DownloadsDB(Context paramContext) {
this.mHelper = new DownloadsContentDBHelper(paramContext);
final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
// Query for the version code, the row ID of the metadata (for future
// updating) the status and the flags
Cursor cur = sqldb.rawQuery("SELECT " +
MetadataColumns.APKVERSION + "," +
BaseColumns._ID + "," +
MetadataColumns.DOWNLOAD_STATUS + "," +
MetadataColumns.FLAGS +
" FROM "
+ MetadataColumns.TABLE_NAME + " LIMIT 1", null);
if (null != cur && cur.moveToFirst()) {
mVersionCode = cur.getInt(0);
mMetadataRowID = cur.getLong(1);
mStatus = cur.getInt(2);
mFlags = cur.getInt(3);
cur.close();
}
mDownloadsDB = this;
}
private void createTablesV2(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_CONNECTION + " (" +
BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
ConnectionColumns.NAME + " TEXT," +
ConnectionColumns.TYPE + " TEXT," +
ConnectionColumns.SCHEME + " TEXT," +
ConnectionColumns.PATH + " TEXT," +
ConnectionColumns.HOST + " TEXT," +
ConnectionColumns.PORT + " INTEGER," +
ConnectionColumns.USERNAME + " TEXT," +
ConnectionColumns.PASSWORD + " TEXT," +
ConnectionColumns.ANONYMOUS_LOGIN + " BOOLEAN," +
"UNIQUE (" + ConnectionColumns.NAME + ", " + ConnectionColumns.HOST + ", " + ConnectionColumns.PATH + ") ON CONFLICT REPLACE " +
")");
addDefaultServer(db);
}
public static String getNameForPlaylist(@NonNull final Context context, final long id) {
try {
Cursor cursor = context.getContentResolver().query(EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.PlaylistsColumns.NAME},
BaseColumns._ID + "=?",
new String[]{String.valueOf(id)},
null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return cursor.getString(0);
}
} finally {
cursor.close();
}
}
} catch (SecurityException ignored) {
}
return "";
}
public static String getNameForPlaylist(@NonNull final Context context, final long id) {
try {
Cursor cursor = context.getContentResolver().query(EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.PlaylistsColumns.NAME},
BaseColumns._ID + "=?",
new String[]{String.valueOf(id)},
null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return cursor.getString(0);
}
} finally {
cursor.close();
}
}
} catch (SecurityException ignored) {
}
return "";
}
public static final int getSongCountForPlaylist(final Context context, final long playlistId) {
Cursor c = context.getContentResolver().query(
MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId),
new String[]{BaseColumns._ID}, MUSIC_ONLY_SELECTION, null, null);
if (c != null) {
int count = 0;
if (c.moveToFirst()) {
count = c.getCount();
}
c.close();
c = null;
return count;
}
return 0;
}
/**
* 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;
}
public void updateConnections() {
Cursor cursor = null;
mRoots.clear();
try {
cursor = getContext().getContentResolver().query(ExplorerProvider.buildConnection(), null, null, null, null);
while (cursor.moveToNext()) {
int id = getCursorInt(cursor, BaseColumns._ID);
NetworkConnection networkConnection = NetworkConnection.fromConnectionsCursor(cursor);
mRoots.put(networkConnection.getHost(), networkConnection);
}
} catch (Exception e) {
Log.w(TAG, "Failed to load some roots from " + ExplorerProvider.AUTHORITY + ": " + e);
Crashlytics.logException(e);
} finally {
IoUtils.closeQuietly(cursor);
}
notifyRootsChanged(getContext());
}
public boolean onPopupMenuItemClick(MenuItem item, int position) {
final Cursor cursor = mAdapter.getItem(position);
int connection_id = getCursorInt(cursor, BaseColumns._ID);
NetworkConnection networkConnection = NetworkConnection.fromConnectionsCursor(cursor);
final int id = item.getItemId();
switch (id) {
case R.id.menu_edit:
editConnection(connection_id);
return true;
case R.id.menu_delete:
if(!networkConnection.type.equals(SERVER)) {
deleteConnection(connection_id);
} else {
((BaseActivity)getActivity())
.showSnackBar("Default server connection can't be deleted",
Snackbar.LENGTH_SHORT);
}
return true;
default:
return false;
}
}
private void createTablesV3(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_STORAGE + " (" +
BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
StorageColumns.NAME + " TEXT," +
StorageColumns.TYPE + " TEXT," +
StorageColumns.SCHEME + " TEXT," +
StorageColumns.PATH + " TEXT," +
StorageColumns.HOST + " TEXT," +
StorageColumns.PORT + " INTEGER," +
StorageColumns.USERNAME + " TEXT," +
StorageColumns.PASSWORD + " TEXT," +
StorageColumns.ANONYMOUS_LOGIN + " BOOLEAN," +
"UNIQUE (" + StorageColumns.NAME + ", " + StorageColumns.HOST + ", " + StorageColumns.PATH + ") ON CONFLICT REPLACE " +
")");
}
public void updateConnections() {
Cursor cursor = null;
mRoots.clear();
try {
cursor = getContext().getContentResolver().query(ExplorerProvider.buildConnection(), null, null, null, null);
while (cursor.moveToNext()) {
int id = getCursorInt(cursor, BaseColumns._ID);
NetworkConnection networkConnection = NetworkConnection.fromConnectionsCursor(cursor);
mRoots.put(networkConnection.getHost(), networkConnection);
}
} catch (Exception e) {
Log.w(TAG, "Failed to load some roots from " + ExplorerProvider.AUTHORITY + ": " + e);
CrashReportingManager.logException(e);
} finally {
IoUtils.closeQuietly(cursor);
}
notifyRootsChanged(getContext());
}
private void createTablesV2(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_CONNECTION + " (" +
BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
ConnectionColumns.NAME + " TEXT," +
ConnectionColumns.TYPE + " TEXT," +
ConnectionColumns.SCHEME + " TEXT," +
ConnectionColumns.PATH + " TEXT," +
ConnectionColumns.HOST + " TEXT," +
ConnectionColumns.PORT + " INTEGER," +
ConnectionColumns.USERNAME + " TEXT," +
ConnectionColumns.PASSWORD + " TEXT," +
ConnectionColumns.ANONYMOUS_LOGIN + " BOOLEAN," +
"UNIQUE (" + ConnectionColumns.NAME + ", " + ConnectionColumns.HOST + ", " + ConnectionColumns.PATH + ") ON CONFLICT REPLACE " +
")");
addDefaultServer(db);
}
public boolean onPopupMenuItemClick(MenuItem item, int position) {
final Cursor cursor = mAdapter.getItem(position);
int connection_id = getCursorInt(cursor, BaseColumns._ID);
NetworkConnection networkConnection = NetworkConnection.fromConnectionsCursor(cursor);
final int id = item.getItemId();
switch (id) {
case R.id.menu_edit:
editConnection(connection_id);
return true;
case R.id.menu_delete:
if(!networkConnection.type.equals(SERVER)) {
deleteConnection(connection_id);
} else {
((BaseActivity)getActivity())
.showSnackBar("Default server connection can't be deleted",
Snackbar.LENGTH_SHORT);
}
return true;
default:
return false;
}
}
public static NetworkConnection fromConnectionId(Context context, int id) {
Cursor cursor = null;
NetworkConnection networkConnection = null;
try {
cursor = context.getContentResolver()
.query(ExplorerProvider.buildConnection(), null,
BaseColumns._ID + "=? "
, new String[]{Integer.toString(id)}, null);
if (null != cursor && cursor.moveToFirst()) {
networkConnection = NetworkConnection.fromConnectionsCursor(cursor);
}
} catch (Exception e) {
Log.w(TAG, "Failed to load some roots from " + NetworkStorageProvider.AUTHORITY + ": " + e);
Crashlytics.logException(e);
} finally {
IoUtils.closeQuietly(cursor);
}
return networkConnection;
}
public void updateConnections() {
Cursor cursor = null;
mRoots.clear();
try {
cursor = getContext().getContentResolver().query(ExplorerProvider.buildConnection(), null, null, null, null);
while (cursor.moveToNext()) {
int id = getCursorInt(cursor, BaseColumns._ID);
NetworkConnection networkConnection = NetworkConnection.fromConnectionsCursor(cursor);
mRoots.put(networkConnection.getHost(), networkConnection);
}
} catch (Exception e) {
Log.w(TAG, "Failed to load some roots from " + ExplorerProvider.AUTHORITY + ": " + e);
Crashlytics.logException(e);
} finally {
IoUtils.closeQuietly(cursor);
}
notifyRootsChanged(getContext());
}
private void createTablesV2(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_CONNECTION + " (" +
BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
ConnectionColumns.NAME + " TEXT," +
ConnectionColumns.TYPE + " TEXT," +
ConnectionColumns.SCHEME + " TEXT," +
ConnectionColumns.PATH + " TEXT," +
ConnectionColumns.HOST + " TEXT," +
ConnectionColumns.PORT + " INTEGER," +
ConnectionColumns.USERNAME + " TEXT," +
ConnectionColumns.PASSWORD + " TEXT," +
ConnectionColumns.ANONYMOUS_LOGIN + " BOOLEAN," +
"UNIQUE (" + ConnectionColumns.NAME + ", " + ConnectionColumns.HOST + ", " + ConnectionColumns.PATH + ") ON CONFLICT REPLACE " +
")");
addDefaultServer(db);
}
private void createTablesV3(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_STORAGE + " (" +
BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
StorageColumns.NAME + " TEXT," +
StorageColumns.TYPE + " TEXT," +
StorageColumns.SCHEME + " TEXT," +
StorageColumns.PATH + " TEXT," +
StorageColumns.HOST + " TEXT," +
StorageColumns.PORT + " INTEGER," +
StorageColumns.USERNAME + " TEXT," +
StorageColumns.PASSWORD + " TEXT," +
StorageColumns.ANONYMOUS_LOGIN + " BOOLEAN," +
"UNIQUE (" + StorageColumns.NAME + ", " + StorageColumns.HOST + ", " + StorageColumns.PATH + ") ON CONFLICT REPLACE " +
")");
}
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 performWriteContactsToPhoneBookInternal(ArrayList<TLRPC.TL_contact> contactsArray) {
Cursor cursor = null;
try {
if (!hasContactsPermission()) {
return;
}
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, systemAccount.name).appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, systemAccount.type).build();
cursor = ApplicationLoader.applicationContext.getContentResolver().query(rawContactUri, new String[]{BaseColumns._ID, ContactsContract.RawContacts.SYNC2}, null, null, null);
SparseLongArray bookContacts = new SparseLongArray();
if (cursor != null) {
while (cursor.moveToNext()) {
bookContacts.put(cursor.getInt(1), cursor.getLong(0));
}
cursor.close();
cursor = null;
for (int a = 0; a < contactsArray.size(); a++) {
TLRPC.TL_contact u = contactsArray.get(a);
if (bookContacts.indexOfKey(u.user_id) < 0) {
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(u.user_id);
addContactToPhoneBook(user, false);
}
}
}
} catch (Exception e) {
FileLog.e(e);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public static Summary query(long id) {
List<Summary> result = CacheDatabase.queryList(Summary.class, BaseColumns._ID + " = " + String.valueOf(id), "limit 1");
if (Utils.isNotEmpty(result)) {
return result.get(0);
}
return null;
}
public static Content query(long id) {
List<Content> result = CacheDatabase.queryList(Content.class, BaseColumns._ID + " = " + String.valueOf(id), "limit 1");
if (Utils.isNotEmpty(result)) {
return result.get(0);
}
return null;
}