下面列出了怎么用android.database.Cursor的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @return certificate id or -1 if not found
*/
public long getCertificateId(byte[] certificateBytes){
Formatter formatter = new Formatter();
for (byte b : Sha256Helper.sha256(certificateBytes)){
formatter.format("%02x", b);
}
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.query(TABLE_CERTIFICATES,
new String[]{COLUMN_ID},
COLUMN_FINGERPRINT + "=?", new String[]{formatter.toString()},
null, null, null);
long returnValue;
if (c.moveToFirst()){
returnValue = c.getLong(0);
} else {
returnValue = -1;
}
c.close();
db.close();
return returnValue;
}
public static ArrayList<MediaListItem> withMediaType(String mediaType) {
ArrayList<MediaListItem> mediaListItems = new ArrayList<>();
SQLiteDatabase database = UpodsApplication.getDatabaseManager().getReadableDatabase();
String[] args = {mediaType};
String table = "radio_stations";
if (mediaType.equals(TYPE_PODCAST)) {
table = "podcasts";
}
Cursor cursor = database.rawQuery("SELECT r.id, r.name, m.list_type FROM " + table + " as r\n" +
"LEFT JOIN media_list as m ON r.id = m.media_id\n" +
"WHERE m.media_type = ?", args);
while (cursor.moveToNext()) {
MediaListItem mediaListItem = new MediaListItem();
mediaListItem.isExistsInDb = true;
mediaListItem.id = cursor.getLong(cursor.getColumnIndex("id"));
mediaListItem.mediaItemName = cursor.getString(cursor.getColumnIndex("name"));
mediaListItem.listType = cursor.getString(cursor.getColumnIndex("list_type"));
mediaListItems.add(mediaListItem);
}
cursor.close();
return mediaListItems;
}
public void setData(Cursor cursor){
mDocumentInfo = DocumentInfo.fromDirectoryCursor(cursor);
final String docAuthority = getCursorString(cursor, RootCursorWrapper.COLUMN_AUTHORITY);
final String docId = getCursorString(cursor, Document.COLUMN_DOCUMENT_ID);
final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
final String docPath = getCursorString(cursor, Document.COLUMN_PATH);
final String docDisplayName = getCursorString(cursor, Document.COLUMN_DISPLAY_NAME);
final int docIcon = getCursorInt(cursor, Document.COLUMN_ICON);
final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
mIconHelper.stopLoading(iconThumb);
iconMimeBackground.setVisibility(View.VISIBLE);
iconMimeBackground.setBackgroundColor(IconColorUtils.loadMimeColor(mContext, docMimeType, docAuthority, docId, mDefaultColor));
iconThumb.animate().cancel();
iconThumb.setAlpha(0f);
final Uri uri = DocumentsContract.buildDocumentUri(docAuthority, docId);
mIconHelper.loadThumbnail(uri, docPath, docMimeType, docFlags, docIcon, iconMime, iconThumb, iconMimeBackground);
}
public static long getLastQueryDate() {
// Open the database
SQLiteDatabase db = DatabaseHelper.getInstance(GlobalApplication.getAppContext()).getReadableDatabase();
// Query the database
Cursor cursor = db.rawQuery("select * from " + USER_INFO, null);
// If the query returned anything, return true, else return false
long date = 0;
if ( (cursor != null) && (cursor.getCount() > 0) ) {
cursor.moveToFirst();
date = cursor.getLong(2);
cursor.close();
LogUtil.log("UserInfoDao", "Last Query: " + date);
}
return date;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor cursor;
switch (URI_MATCHER.match(uri)) {
case CONNECTION_ALL:
cursor = mDatabase.query(TABLE_NAME_CONNECTIONS, projection, selection, selectionArgs, null, null, sortOrder);
break;
case CONNECTION_ONE:
String xid = uri.getPathSegments().get(1);
cursor = mDatabase.query(TABLE_NAME_CONNECTIONS, projection, BaseColumns._ID + " = ?", new String[] { xid }, null, null, sortOrder);
break;
case QUERY_ALL:
cursor = mDatabase.query(TABLE_NAME_QUERIES, projection, selection, selectionArgs, null, null, sortOrder);
break;
case QUERY_ONE:
String yid = uri.getPathSegments().get(1);
cursor = mDatabase.query(TABLE_NAME_QUERIES, projection, BaseColumns._ID + " = ?", new String[] { yid }, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Unsupported URI:" + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
/** 是否需要升级表 */
public static boolean isNeedUpgradeTable(SQLiteDatabase db, TableEntity table) {
if (!isTableExists(db, table.tableName)) return true;
Cursor cursor = db.rawQuery("select * from " + table.tableName, null);
if (cursor == null) return false;
try {
int columnCount = table.getColumnCount();
if (columnCount == cursor.getColumnCount()) {
for (int i = 0; i < columnCount; i++) {
if (table.getColumnIndex(cursor.getColumnName(i)) == -1) {
return true;
}
}
} else {
return true;
}
return false;
} finally {
cursor.close();
}
}
@Override
protected String doInBackground(final Void... params) {
String ret = null;
if (CallMeter.hasPermission(ctx, Manifest.permission.READ_CONTACTS)) {
// resolve names only when permission is granted
try {
//noinspection ConstantConditions
Cursor c = ctx.getContentResolver().query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, num),
new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
if (c != null) {
if (c.moveToFirst()) {
ret = c.getString(0);
}
c.close();
}
} catch (Exception e) {
Log.e(TAG, "error loading name", e);
}
}
return ret;
}
/**
* Function to get one aya tafser
*
* @param soraID Sora id
* @param ayaID Aya id
* @param book Tafseer book number
* @return Aya information with tafseer
*/
public AyaTafseer getAyaTafseer(int soraID, int ayaID, int book, String ayaText) {
AyaTafseer ayaTafseer = null;
SQLiteDatabase db = openDB(TAFSEER_DATABASE + "/tafseer" + book + ".sqlite");
String sql = "select tafseer from ayatafseer where soraid = " + soraID + " and ayaid = " + ayaID + " ;";
Cursor cursor = db.rawQuery(sql, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
ayaTafseer = new AyaTafseer(soraID,
ayaID, cursor.getString(0).equals("") ? "لا يوجد تفسير" : cursor.getString(0),
ayaText);
cursor.moveToNext();
}
cursor.close();
closeDB(db);
return ayaTafseer;
}
/**
* Return a Cursor contains all RegisteredActionParameter records which matches the parameters.
*
* @param parameterName
* is the parameter name, or null to fetch any parameterName.
* @param actionID
* is the action id, or null to fetch any actionID.
* @param dataTypeID
* is the dataType id, or null to fetch any dataTypeID.
* @return a Cursor contains all RegisteredActionParameter records which matches the parameters.
*/
public Cursor fetchAll(String parameterName, Long actionID, Long dataTypeID) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(DATABASE_TABLE);
qb.appendWhere("1=1");
if (parameterName != null) {
qb.appendWhere(" AND " + KEY_ACTIONPARAMETERNAME + " = ");
qb.appendWhereEscapeString(parameterName);
}
if (actionID != null) {
qb.appendWhere(" AND " + KEY_ACTIONID + " = " + actionID);
}
if (dataTypeID != null) {
qb.appendWhere(" AND " + KEY_DATATYPEID + " = " + dataTypeID);
}
// Not using additional selections, selectionArgs, groupBy, having, orderBy, set them to null.
return qb.query(database, KEYS, null, null, null, null, null);
}
public Server getGoodRandomServer(String country) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor;
if (country != null) {
cursor = db.rawQuery("SELECT * FROM "
+ TABLE_SERVERS
+ " WHERE "
+ KEY_QUALITY
+ " <> 0 AND "
+ KEY_COUNTRY_LONG
+ " = ?", new String[] {country});
} else {
cursor = db.rawQuery("SELECT * FROM "
+ TABLE_SERVERS
+ " WHERE "
+ KEY_QUALITY
+ " <> 0", null);
}
return parseGoodRandomServer(cursor, db);
}
public Cursor swapCursor(Cursor newCursor) {
if (newCursor == mCursor) {
return null;
}
final Cursor oldCursor = mCursor;
if (oldCursor != null && mDataSetObserver != null) {
oldCursor.unregisterDataSetObserver(mDataSetObserver);
}
mCursor = newCursor;
if (mCursor != null) {
if (mDataSetObserver != null) {
mCursor.registerDataSetObserver(mDataSetObserver);
}
rowIdColumn = newCursor.getColumnIndexOrThrow("_id");
dataIsValid = true;
notifyDataSetChanged();
} else {
rowIdColumn = -1;
dataIsValid = false;
notifyDataSetChanged();
}
return oldCursor;
}
/**
* Get the file path from the Media Content Uri for video, audio or images.
*
* @param mediaContentUri Media content Uri.
**/
public static String getPathForMediaUri(Context context, Uri mediaContentUri) {
Cursor cur = null;
String path = null;
try {
String[] projection = {MediaColumns.DATA};
cur = context.getContentResolver().query(mediaContentUri, projection, null, null, null);
if (cur != null && cur.getCount() != 0) {
cur.moveToFirst();
path = cur.getString(cur.getColumnIndexOrThrow(MediaColumns.DATA));
}
// Log.v( TAG, "#getRealPathFromURI Path: " + path );
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cur != null && !cur.isClosed())
cur.close();
}
return path;
}
public static Cursor makePlaylistSongCursor(@NonNull final Context context, final int playlistId) {
try {
return context.getContentResolver().query(
MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId),
new String[]{
MediaStore.Audio.Playlists.Members.AUDIO_ID,// 0
AudioColumns.TITLE,// 1
AudioColumns.TRACK,// 2
AudioColumns.YEAR,// 3
AudioColumns.DURATION,// 4
AudioColumns.DATA,// 5
AudioColumns.DATE_MODIFIED,// 6
AudioColumns.ALBUM_ID,// 7
AudioColumns.ALBUM,// 8
AudioColumns.ARTIST_ID,// 9
AudioColumns.ARTIST,// 10
MediaStore.Audio.Playlists.Members._ID // 11
}, SongLoader.BASE_SELECTION, null,
MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER);
} catch (SecurityException e) {
return null;
}
}
@Override
public List<QiscusComment> searchComments(String query, long roomId, int limit, int offset) {
String sql = "SELECT * FROM "
+ QiscusDb.CommentTable.TABLE_NAME + " WHERE "
+ QiscusDb.CommentTable.COLUMN_ROOM_ID + " = " + roomId + " AND "
+ QiscusDb.CommentTable.COLUMN_MESSAGE + " LIKE '%" + query + "%' " + " AND "
+ QiscusDb.CommentTable.COLUMN_HARD_DELETED + " = " + 0
+ " ORDER BY " + QiscusDb.CommentTable.COLUMN_TIME + " DESC "
+ " LIMIT " + limit + " OFFSET " + offset;
Cursor cursor = sqLiteReadDatabase.rawQuery(sql, null);
List<QiscusComment> qiscusComments = new ArrayList<>();
while (cursor.moveToNext()) {
QiscusComment qiscusComment = QiscusDb.CommentTable.parseCursor(cursor);
QiscusRoomMember qiscusRoomMember = getMember(qiscusComment.getSenderEmail());
if (qiscusRoomMember != null) {
qiscusComment.setSender(qiscusRoomMember.getUsername());
qiscusComment.setSenderAvatar(qiscusRoomMember.getAvatar());
}
qiscusComments.add(qiscusComment);
}
cursor.close();
return qiscusComments;
}
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 void create(@NonNull SQLiteDatabase database) {
String orderQuery = "SELECT COUNT(" + C_ID + ") AS count FROM " + TABLE_NAME;
Cursor c = database.rawQuery(orderQuery, null);
int currentItemCount = 0;
if (c != null) {
if (c.moveToFirst()) {
currentItemCount = c.getInt(c.getColumnIndexOrThrow("count"));
}
c.close();
}
ContentValues values = new ContentValues();
values.put(C_TEXT, text);
values.put(C_ORDER, currentItemCount);
//NOTE: in a real instance you would get the generated C_ID and store it in the id field
database.insert(TABLE_NAME, null, values);
}
private void assertAccountBlotterColumn(Account account, DatabaseHelper.BlotterColumns column, long... values) {
WhereFilter filter = createBlotterForAccountFilter(account);
Cursor c = db.getBlotterForAccount(filter);
try {
int i = 0;
while (c.moveToNext()) {
if (i >= values.length) {
fail("Too many rows " + c.getCount() + ". Expected " + values.length);
}
long expectedAmount = values[i++];
long amount = c.getLong(column.ordinal());
assertEquals("Blotter row " + i, expectedAmount, amount);
}
if (i != values.length) {
fail("Too few rows " + c.getCount() + ". Expected " + values.length);
}
} finally {
c.close();
}
}
public static boolean exists(Context context, Uri self) {
final ContentResolver resolver = context.getContentResolver();
Cursor c = null;
try {
c = resolver.query(self, new String[] {
DocumentsContract.Document.COLUMN_DOCUMENT_ID }, null, null, null);
return c.getCount() > 0;
} catch (Exception e) {
Log.w(TAG, "Failed query: " + e);
return false;
} finally {
closeQuietly(c);
}
}
public static File getFromMediaUri(ContentResolver resolver, Uri uri) {
if (uri == null) return null;
if (SCHEME_FILE.equals(uri.getScheme())) {
return new File(uri.getPath());
} else if (SCHEME_CONTENT.equals(uri.getScheme())) {
final String[] filePathColumn = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME };
Cursor cursor = null;
try {
cursor = resolver.query(uri, filePathColumn, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final int columnIndex = (uri.toString().startsWith("content://com.google.android.gallery3d")) ?
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME) :
cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
// Picasa image on newer devices with Honeycomb and up
if (columnIndex != -1) {
String filePath = cursor.getString(columnIndex);
if (!TextUtils.isEmpty(filePath)) {
return new File(filePath);
}
}
}
} catch (SecurityException ignored) {
// Nothing we can do
} finally {
if (cursor != null) cursor.close();
}
}
return null;
}
private void updateAlbumCover(long albumId, String title) {
// Get the previous cover path
String oldCoverPath = null;
String[] proj = new String[]{AnchorContract.AlbumEntry.COLUMN_COVER_PATH};
String sel = AnchorContract.AlbumEntry._ID + "=?";
String[] selArgs = {Long.toString(albumId)};
Cursor c = mContext.getContentResolver().query(AnchorContract.AlbumEntry.CONTENT_URI,
proj, sel, selArgs, null);
if (c == null || c.getCount() < 1) {
return;
}
if (c.moveToFirst()) {
oldCoverPath = c.getString(c.getColumnIndex(AnchorContract.AlbumEntry.COLUMN_COVER_PATH));
}
c.close();
if (oldCoverPath == null || !(new File(mDirectory.getAbsolutePath() + File.separator + oldCoverPath).exists())) {
// Search for a cover in the album directory
File albumDir = new File(mDirectory.getAbsolutePath() + File.separator + title);
String coverPath = Utils.getImagePath(albumDir);
if (coverPath != null) {
coverPath = coverPath.replace(mDirectory.getAbsolutePath(), "");
}
// Update the album cover path in the albums table
ContentValues values = new ContentValues();
values.put(AnchorContract.AlbumEntry.COLUMN_COVER_PATH, coverPath);
mContext.getContentResolver().update(AnchorContract.AlbumEntry.CONTENT_URI, values, sel, selArgs);
}
}
public MyAdapter(final Context context, final int layout, final Cursor c,
final String[] from, final int[] to) {
super(context, layout, c, from, to, 0 /* flags */);
if (null != c) {
final String alphabet = context.getString(R.string.user_dict_fast_scroll_alphabet);
final int wordColIndex = c.getColumnIndexOrThrow(UserDictionary.Words.WORD);
mIndexer = new AlphabetIndexer(c, wordColIndex, alphabet);
}
setViewBinder(mViewBinder);
}
public ConversationAdater(Context context, Cursor cursor,
XmppBinder xmppServiceBinder) {
// TODO Auto-generated constructor stub
super(context, cursor, true);
mContext = context;
mXmppServiceBinder = xmppServiceBinder;
}
private void changeColor(int pos, View change) {
Cursor csr = getCursor();
csr.moveToPosition(pos);
int color = csr.getInt(csr.getColumnIndexOrThrow("color"));
if(sdkVersion < android.os.Build.VERSION_CODES.JELLY_BEAN) {
change.setBackgroundDrawable(EnvelopesAdapter.getColorStateDrawable(color));
} else {
change.setBackground(EnvelopesAdapter.getColorStateDrawable(color));
}
}
public String getContactName(String contactId) {
contactId = sanitizeContactId(contactId);
Cursor c = getReadableDatabase().rawQuery("SELECT " + ContactColumns.CONTACT_NAME +
" FROM " + CONTACTS_TABLE_NAME + " WHERE " + ContactColumns.CONTACT_ID + " = '" +
contactId + "'", null);
String result = "";
if (c.moveToNext()) {
result = c.getString(0);
}
c.close();
return result;
}
/**
* Return record center position
*
* @param recordId record identifier
* @param maxAccuracy ignore measurements with
* @return
*/
public double[] getRecordCenterPosition(int recordId, double maxAccuracy) {
SQLiteDatabase database = storage.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT AVG(" +
Storage.Leq.COLUMN_LATITUDE + ") LATAVG, AVG(" +
Storage.Leq.COLUMN_LONGITUDE + ") LONGAVG FROM " + Storage.Leq.TABLE_NAME + " L " +
"WHERE L." + Storage.Leq.COLUMN_RECORD_ID + " = ? AND " + Storage.Leq
.COLUMN_ACCURACY + " BETWEEN 1 AND " +
"? ", new String[]{String.valueOf(recordId), String.valueOf(maxAccuracy)});
try {
if (cursor.moveToNext()) {
Double latavg = cursor.getDouble(0);
Double longavg = cursor.getDouble(1);
if(latavg.equals(0.0) && longavg.equals(0.0)) {
return null;
} else {
return new double[]{latavg, longavg};
}
}
} catch (IllegalStateException ex) {
// Ignore
} finally {
cursor.close();
}
return null;
}
public int getMessageCountForThread(long threadId, long beforeTime) {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
String[] cols = new String[] {"COUNT(*)"};
String query = THREAD_ID + " = ? AND " + DATE_RECEIVED + " < ?";
String[] args = new String[]{String.valueOf(threadId), String.valueOf(beforeTime)};
try (Cursor cursor = db.query(TABLE_NAME, cols, query, args, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
return cursor.getInt(0);
}
}
return 0;
}
private <T extends Persistable> List<T> rawQuery(
Persistable.Converter<T> converter, String query, String... args) {
Cursor cursor = null;
List<T> items = new ArrayList<>();
try {
cursor = db.query(query, args);
while (cursor.moveToNext()) {
items.add(cursorToObject(converter, cursor));
}
} finally {
closeQuietly(cursor);
}
return items;
}
@Override
public void onItemClick(final AdapterView<?> parent, final View view,
final int position, final long id) {
final Cursor c = (Cursor) parent.getItemAtPosition(position);
final User u = User.parse(c);
if (u != null) {
if (AppContext.DEBUG) {
log("userId=" + u.id + " username=" + u.screenName);
}
ActionManager.doProfile(this.mContext, u);
}
}
protected long getImageForBucketCleared(long bucketId) throws FileNotFoundException {
final ContentResolver resolver = getContext().getContentResolver();
Cursor cursor = null;
try {
cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
ImagesBucketThumbnailQuery.PROJECTION, ImageColumns.BUCKET_ID + "=" + bucketId,
null, ImageColumns.DATE_MODIFIED + " DESC");
if (cursor.moveToFirst()) {
return cursor.getLong(ImagesBucketThumbnailQuery._ID);
}
} finally {
IoUtils.closeQuietly(cursor);
}
throw new FileNotFoundException("No video found for bucket");
}
@Override
public void run() {
try {
final UpdateHelper updateHelper = new UpdateHelper();
final Query query = new Query().setFilterById(mId);
setIndeterminate(true);
while (!isInterrupted()) {
final Cursor cursor = mDownloadManagerWrapper.query(query);
if (null == cursor) {
// Can't contact DownloadManager: this should never happen.
return;
}
try {
if (cursor.moveToNext()) {
final int columnBytesDownloadedSoFar = cursor.getColumnIndex(
DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
final int bytesDownloadedSoFar =
cursor.getInt(columnBytesDownloadedSoFar);
updateHelper.setProgressFromAnotherThread(bytesDownloadedSoFar);
} else {
// Download has finished and DownloadManager has already been asked to
// clean up the db entry.
updateHelper.setProgressFromAnotherThread(getMax());
return;
}
} finally {
cursor.close();
}
Thread.sleep(REPORT_PERIOD);
}
} catch (InterruptedException e) {
// Do nothing and terminate normally.
}
}