android.database.Cursor Java Examples
The following examples show how to use
android.database.Cursor.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServerDatabaseHandler.java From an2linuxclient with GNU General Public License v3.0 | 9 votes |
/** * @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; }
Example #2
Source File: NameLoader.java From callmeter with GNU General Public License v3.0 | 7 votes |
@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; }
Example #3
Source File: MediaListItem.java From uPods-android with Apache License 2.0 | 7 votes |
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; }
Example #4
Source File: DBUtils.java From okhttp-OkGo with Apache License 2.0 | 6 votes |
/** 是否需要升级表 */ 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(); } }
Example #5
Source File: AccountBlotterTest.java From financisto with GNU General Public License v2.0 | 6 votes |
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(); } }
Example #6
Source File: RecentsAdapter.java From FireFiles with Apache License 2.0 | 6 votes |
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); }
Example #7
Source File: UserInfoDao.java From narrate-android with Apache License 2.0 | 6 votes |
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; }
Example #8
Source File: RegisteredActionParameterDbAdapter.java From LibreTasks with Apache License 2.0 | 6 votes |
/** * 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); }
Example #9
Source File: MongoBrowserProvider.java From MongoExplorer with MIT License | 6 votes |
@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; }
Example #10
Source File: ItemDAO.java From RecyclerExt with Apache License 2.0 | 6 votes |
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); }
Example #11
Source File: DatabaseAccess.java From QuranAndroid with GNU General Public License v3.0 | 6 votes |
/** * 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; }
Example #12
Source File: DBHelper.java From EasyVPN-Free with GNU General Public License v3.0 | 6 votes |
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); }
Example #13
Source File: CursorAdapter.java From watchlist with Apache License 2.0 | 6 votes |
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; }
Example #14
Source File: Utils.java From android-utils with MIT License | 6 votes |
/** * 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; }
Example #15
Source File: ContactsServicePlugin.java From flutter_contacts with MIT License | 6 votes |
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; }
Example #16
Source File: QiscusDataBaseHelper.java From qiscus-sdk-android with Apache License 2.0 | 6 votes |
@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; }
Example #17
Source File: PlaylistSongLoader.java From Orin with GNU General Public License v3.0 | 6 votes |
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; } }
Example #18
Source File: ArtistInfoDao.java From SweetMusicPlayer with Apache License 2.0 | 5 votes |
/** @inheritdoc */ @Override public void readEntity(Cursor cursor, ArtistInfo entity, int offset) { entity.setArtistId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setArtist(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setNumSongs(cursor.isNull(offset + 2) ? null : cursor.getInt(offset + 2)); }
Example #19
Source File: Shillelagh.java From shillelagh with Apache License 2.0 | 5 votes |
/** * The equivalent of calling * {@link SQLiteDatabase#query(boolean, String, String[], String, String[], String, String, * String, String, android.os.CancellationSignal)} * and then calling {@link Shillelagh#map(Class, android.database.Cursor)} on the result * * Only available for API 16+ */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public <T extends List<M>, M> T query(Class<? extends M> tableObject, boolean distinct, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal) { Cursor results = sqliteOpenHelper.getReadableDatabase() .query(distinct, getTableName(tableObject), columns, selection, selectionArgs, groupBy, having, orderBy, limit, cancellationSignal); return map(tableObject, results); }
Example #20
Source File: MediaStoreAdapter.java From libcommon with Apache License 2.0 | 5 votes |
@Override public View newView(final Context context, final Cursor cursor, final ViewGroup parent) { // this method is called within UI thread and should return as soon as possible final View view = mInflater.inflate(mLayoutId, parent, false); getViewHolder(view); return view; }
Example #21
Source File: BlackListDao.java From sealtalk-android with MIT License | 5 votes |
/** @inheritdoc */ @Override public void readEntity(Cursor cursor, BlackList entity, int offset) { entity.setUserId(cursor.getString(offset + 0)); entity.setStatus(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setTimestamp(cursor.isNull(offset + 2) ? null : cursor.getLong(offset + 2)); }
Example #22
Source File: CropUtil.java From ImageChoose with MIT License | 5 votes |
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; }
Example #23
Source File: SongLoader.java From VinylMusicPlayer with GNU General Public License v3.0 | 5 votes |
@Nullable public static Cursor makeSongCursorFromPaths(@NonNull final Context context, @NonNull ArrayList<String> paths) { // Exclude blacklist paths.removeAll(BlacklistStore.getInstance(context).getPaths()); int remaining = paths.size(); int processed = 0; ArrayList<Cursor> cursors = new ArrayList<>(); final String sortOrder = PreferenceUtil.getInstance().getSongSortOrder(); while (remaining > 0) { final int currentBatch = Math.min(BATCH_SIZE, remaining); StringBuilder selection = new StringBuilder(); selection.append(BASE_SELECTION + " AND " + MediaStore.Audio.AudioColumns.DATA + " IN (?"); for (int i = 1; i < currentBatch; i++) { selection.append(",?"); } selection.append(")"); try { Cursor cursor = context.getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, BASE_PROJECTION, selection.toString(), paths.subList(processed, processed + currentBatch).toArray(new String[currentBatch]), sortOrder ); if (cursor != null) {cursors.add(cursor);}; } catch (SecurityException ignored) { } remaining -= currentBatch; processed += currentBatch; } if (cursors.isEmpty()) {return null;} return new MergeCursor(cursors.toArray(new Cursor[cursors.size()])); }
Example #24
Source File: LogsFragment.java From callmeter with GNU General Public License v3.0 | 5 votes |
@Override public Loader<Cursor> onCreateLoader(final int id, final Bundle args) { Log.d(TAG, "onCreateLoader(", id, ",", args, ")"); getActivity().setProgress(1); String where = null; if (args != null) { where = args.getString("where"); } return new CursorLoader(getActivity(), DataProvider.Logs.CONTENT_URI_JOIN, DataProvider.Logs.PROJECTION_JOIN, where, null, DataProvider.Logs.DATE + " DESC"); }
Example #25
Source File: Synchronizer.java From AudioAnchor with GNU General Public License v3.0 | 5 votes |
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); } }
Example #26
Source File: AppDataDao.java From MinMinGuard with GNU General Public License v3.0 | 5 votes |
/** * @inheritdoc */ @Override public void readEntity(Cursor cursor, AppData entity, int offset) { entity.setPkgName(cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0)); entity.setAdNetworks(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setBlockNum(cursor.isNull(offset + 2) ? null : cursor.getInt(offset + 2)); }
Example #27
Source File: PutOperationTest.java From storio with Apache License 2.0 | 5 votes |
@Test public void updateNotNullFieldToNull() { TestSubscriber<Changes> changesTestSubscriber = new TestSubscriber<Changes>(); storIOContentResolver .observeChangesOfUri(TestItem.CONTENT_URI, BackpressureStrategy.MISSING) .take(2) .subscribe(changesTestSubscriber); Uri insertedUri = contentResolver.insert(TestItem.CONTENT_URI, TestItem.create(null, "value", "optionalValue").toContentValues()); TestItem testItem = TestItem.create(ContentUris.parseId(insertedUri), "value", null); // optional value changes to null PutResult updateResult = storIOContentResolver .put() .object(testItem) .prepare() .executeAsBlocking(); assertThat(updateResult.wasUpdated()).isTrue(); Cursor cursor = contentResolver.query(TestItem.CONTENT_URI, null, null, null, null); Assertions.assertThat(cursor).hasCount(1); cursor.moveToFirst(); assertThat(testItem).isEqualTo(TestItem.fromCursor(cursor)); changesTestSubscriber.awaitTerminalEvent(60, SECONDS); changesTestSubscriber.assertNoErrors(); changesTestSubscriber.assertValues(Changes.newInstance(TestItem.CONTENT_URI), Changes.newInstance(TestItem.CONTENT_URI)); }
Example #28
Source File: UIDbHelper.java From LibreTasks with Apache License 2.0 | 5 votes |
public ModelLog getActionLog(long id) { if (isClosed) { throw new IllegalStateException(TAG + " is closed."); } Cursor cursor = logActionDbAdapter.fetch(id); long logID = getLongFromCursor(cursor, LogDbAdapter.KEY_ID); String logName = getStringFromCursor(cursor, LogActionDbAdapter.KEY_ACTIONEVENTNAME); long logTimestamp = getLongFromCursor(cursor, LogDbAdapter.KEY_TIMESTAMP); String logDesc = getStringFromCursor(cursor, LogDbAdapter.KEY_DESCRIPTION); ModelLog log = new ModelLog(logID, logName, logDesc, R.drawable.icon_action_unknown, logTimestamp, ModelLog.TYPE_ACTION); cursor.close(); return log; }
Example #29
Source File: ContactablesLoaderCallbacks.java From android-BasicContactables with Apache License 2.0 | 5 votes |
@Override public Loader<Cursor> onCreateLoader(int loaderIndex, Bundle args) { // Where the Contactables table excels is matching text queries, // not just data dumps from Contacts db. One search term is used to query // display name, email address and phone number. In this case, the query was extracted // from an incoming intent in the handleIntent() method, via the // intent.getStringExtra() method. // BEGIN_INCLUDE(uri_with_query) String query = args.getString(QUERY_KEY); Uri uri = Uri.withAppendedPath( CommonDataKinds.Contactables.CONTENT_FILTER_URI, query); // END_INCLUDE(uri_with_query) // BEGIN_INCLUDE(cursor_loader) // Easy way to limit the query to contacts with phone numbers. String selection = CommonDataKinds.Contactables.HAS_PHONE_NUMBER + " = " + 1; // Sort results such that rows for the same contact stay together. String sortBy = CommonDataKinds.Contactables.LOOKUP_KEY; return new CursorLoader( mContext, // Context uri, // URI representing the table/resource to be queried null, // projection - the list of columns to return. Null means "all" selection, // selection - Which rows to return (condition rows must match) null, // selection args - can be provided separately and subbed into selection. sortBy); // string specifying sort order // END_INCLUDE(cursor_loader) }
Example #30
Source File: DatabaseAdapter.java From financisto with GNU General Public License v2.0 | 5 votes |
public Attribute getAttribute(long id) { try (Cursor c = db().query(ATTRIBUTES_TABLE, AttributeColumns.NORMAL_PROJECTION, AttributeColumns.ID + "=?", new String[]{String.valueOf(id)}, null, null, null)) { if (c.moveToFirst()) { return Attribute.fromCursor(c); } } return new Attribute(); }