android.database.Cursor

Here are the examples of the java api class android.database.Cursor taken from open source projects.

1. DBReader#getFlattrQueue()

Project: AntennaPod
Source File: DBReader.java
View license
/**
     * Returns the flattr queue as a List of FlattrThings. The list consists of Feeds and FeedItems.
     *
     * @return The flattr queue as a List.
     */
public static List<FlattrThing> getFlattrQueue() {
    Log.d(TAG, "getFlattrQueue() called with: " + "");
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    List<FlattrThing> result = new ArrayList<>();
    // load feeds
    Cursor feedCursor = adapter.getFeedsInFlattrQueueCursor();
    if (feedCursor.moveToFirst()) {
        do {
            result.add(extractFeedFromCursorRow(adapter, feedCursor));
        } while (feedCursor.moveToNext());
    }
    feedCursor.close();
    //load feed items
    Cursor feedItemCursor = adapter.getFeedItemsInFlattrQueueCursor();
    result.addAll(extractItemlistFromCursor(adapter, feedItemCursor));
    feedItemCursor.close();
    adapter.close();
    Log.d(TAG, "Returning flattrQueueIterator for queue with " + result.size() + " items.");
    return result;
}

2. QueryMathTest#testCount()

Project: LitePal
Source File: QueryMathTest.java
View license
public void testCount() {
    int result = DataSupport.count(Student.class);
    int realResult = -100;
    Cursor cursor = DataSupport.findBySQL("select count(1) from " + studentTable);
    if (cursor.moveToFirst()) {
        realResult = cursor.getInt(0);
    }
    cursor.close();
    assertEquals(realResult, result);
    result = DataSupport.where("id > ?", "99").count(studentTable);
    cursor = DataSupport.findBySQL("select count(1) from " + studentTable + " where id > ?", "99");
    if (cursor.moveToFirst()) {
        realResult = cursor.getInt(0);
    }
    cursor.close();
    assertEquals(realResult, result);
    try {
        DataSupport.count("nosuchtable");
        fail();
    } catch (Exception e) {
    }
}

3. QueryMathTest#testAverage()

Project: LitePal
Source File: QueryMathTest.java
View license
public void testAverage() {
    double result = DataSupport.average(Student.class, "age");
    double realResult = -100;
    Cursor cursor = DataSupport.findBySQL("select avg(age) from " + studentTable);
    if (cursor.moveToFirst()) {
        realResult = cursor.getDouble(0);
    }
    cursor.close();
    assertEquals(realResult, result);
    result = DataSupport.where("id > ?", "99").average(studentTable, "age");
    cursor = DataSupport.findBySQL("select avg(age) from " + studentTable + " where id > ?", "99");
    if (cursor.moveToFirst()) {
        realResult = cursor.getDouble(0);
    }
    cursor.close();
    assertEquals(realResult, result);
    try {
        DataSupport.average(Student.class, "nosuchcolumn");
        fail();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

4. QueryMathTest#testMax()

Project: LitePal
Source File: QueryMathTest.java
View license
public void testMax() {
    int result = DataSupport.max(Student.class, "age", Integer.TYPE);
    int realResult = -100;
    Cursor cursor = DataSupport.findBySQL("select max(age) from " + studentTable);
    if (cursor.moveToFirst()) {
        realResult = cursor.getInt(0);
    }
    cursor.close();
    assertEquals(realResult, result);
    result = DataSupport.where("age < ?", "20").max(studentTable, "age", Integer.TYPE);
    cursor = DataSupport.findBySQL("select max(age) from " + studentTable + " where age < ?", "20");
    if (cursor.moveToFirst()) {
        realResult = cursor.getInt(0);
    }
    cursor.close();
    assertEquals(realResult, result);
}

5. QueryMathTest#testMin()

Project: LitePal
Source File: QueryMathTest.java
View license
public void testMin() {
    int result = DataSupport.min(Student.class, "age", Integer.TYPE);
    int realResult = -100;
    Cursor cursor = DataSupport.findBySQL("select min(age) from " + studentTable);
    if (cursor.moveToFirst()) {
        realResult = cursor.getInt(0);
    }
    cursor.close();
    assertEquals(realResult, result);
    result = DataSupport.where("age > ?", "10").min(studentTable, "age", Integer.TYPE);
    cursor = DataSupport.findBySQL("select min(age) from " + studentTable + " where age > ?", "10");
    if (cursor.moveToFirst()) {
        realResult = cursor.getInt(0);
    }
    cursor.close();
    assertEquals(realResult, result);
}

6. QueryMathTest#testSum()

Project: LitePal
Source File: QueryMathTest.java
View license
public void testSum() {
    int result = DataSupport.sum(Student.class, "age", Integer.TYPE);
    int realResult = -100;
    Cursor cursor = DataSupport.findBySQL("select sum(age) from " + studentTable);
    if (cursor.moveToFirst()) {
        realResult = cursor.getInt(0);
    }
    cursor.close();
    assertEquals(realResult, result);
    result = DataSupport.where("age > ?", "15").sum(studentTable, "age", Integer.TYPE);
    cursor = DataSupport.findBySQL("select sum(age) from " + studentTable + " where age > ?", "15");
    if (cursor.moveToFirst()) {
        realResult = cursor.getInt(0);
    }
    cursor.close();
    assertEquals(realResult, result);
}

7. TaskRecorder#getInfo()

View license
private String getInfo(String identifier, String KEY) {
    db = mSQLHelper.getReadableDatabase();
    String selection = KEY_GOOGLE_TASK_IDENTIFIER + "=?";
    String[] selectionArgs = { identifier };
    Cursor cursor = db.query(TASKS_TABLE_NAME, null, selection, selectionArgs, null, null, null);
    int index = cursor.getColumnIndex(KEY);
    if (cursor.isNull(index)) {
        return "0";
    }
    ArrayList<String> list = new ArrayList<String>();
    for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
        if (KEY.equals(KEY_COMPLETED) || KEY.equals(KEY_DELETED)) {
            list.add(String.valueOf(cursor.getInt(index)));
        } else {
            list.add(cursor.getString(index));
        }
    }
    cursor.close();
    return list.get(0);
}

8. MySQLiteHelper#queryAll()

Project: AndroidLife
Source File: MySQLiteHelper.java
View license
/**
     * ????
     *
     * @return List list
     */
public List<SQLiteData> queryAll() {
    List<SQLiteData> allData = new ArrayList<>();
    SQLiteDatabase queryAll = this.getReadableDatabase();
    queryAll.beginTransaction();
    String sql = "select * from " + TB_CAMNTER;
    Cursor result = queryAll.rawQuery(sql, null);
    for (result.moveToFirst(); !result.isAfterLast(); result.moveToNext()) {
        SQLiteData data = new SQLiteData();
        data.id = result.getInt(result.getColumnIndex("_id"));
        data.content = result.getString(result.getColumnIndex("content"));
        allData.add(data);
    }
    queryAll.setTransactionSuccessful();
    queryAll.endTransaction();
    result.close();
    return allData;
}

9. DBReader#getPlaybackHistory()

Project: AntennaPod
Source File: DBReader.java
View license
/**
     * Loads the playback history from the database. A FeedItem is in the playback history if playback of the correpsonding episode
     * has been completed at least once.
     *
     * @return The playback history. The FeedItems are sorted by their media's playbackCompletionDate in descending order.
     * The size of the returned list is limited by {@link #PLAYBACK_HISTORY_SIZE}.
     */
public static List<FeedItem> getPlaybackHistory() {
    Log.d(TAG, "getPlaybackHistory() called");
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    Cursor mediaCursor = adapter.getCompletedMediaCursor(PLAYBACK_HISTORY_SIZE);
    String[] itemIds = new String[mediaCursor.getCount()];
    for (int i = 0; i < itemIds.length && mediaCursor.moveToPosition(i); i++) {
        int index = mediaCursor.getColumnIndex(PodDBAdapter.KEY_FEEDITEM);
        itemIds[i] = Long.toString(mediaCursor.getLong(index));
    }
    mediaCursor.close();
    Cursor itemCursor = adapter.getFeedItemCursor(itemIds);
    List<FeedItem> items = extractItemlistFromCursor(adapter, itemCursor);
    loadAdditionalFeedItemListData(items);
    itemCursor.close();
    adapter.close();
    Collections.sort(items, new PlaybackCompletionDateComparator());
    return items;
}

10. BackupManager#needTransGallery()

Project: HeartBeat
Source File: BackupManager.java
View license
public static boolean needTransGallery(Context context) {
    boolean ret = false;
    Cursor eventImage = DatabaseUtils.query(context, ImageTable.NAME, new String[] { ImageTable.ID, ImageTable.URI }, ImageTable.URI + " like ?", new String[] { "%/%" });
    Log.d(TAG, String.format("?????%d????.", eventImage.getCount()));
    if (eventImage.getCount() > 1)
        ret = true;
    eventImage.close();
    if (ret)
        return true;
    Cursor thoughtImage = DatabaseUtils.query(context, ThoughtResTable.NAME, new String[] { ThoughtResTable.ID, ThoughtResTable.TYPE, ThoughtResTable.PATH, ThoughtResTable.THOUGHT_ID }, ThoughtResTable.PATH + " like ?", new String[] { "%/%" });
    Log.d(TAG, String.format("?????%d????.", thoughtImage.getCount()));
    if (thoughtImage.getCount() > 1)
        ret = true;
    thoughtImage.close();
    return ret;
}

11. FileImageTest#gallery()

View license
List<Track> gallery() {
    List<Track> tracks = new ArrayList<>();
    Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
    if (cursor == null || cursor.getCount() == 0)
        return tracks;
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME);
        int pathIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
        String name = cursor.getString(nameIndex);
        String path = cursor.getString(pathIndex);
        Track track = new Track();
        track.setTitle(name);
        track.setUrl(path);
        tracks.add(track);
    }
    cursor.close();
    return tracks;
}

12. OrgFileTest#testRemoveFileSimple()

Project: mobileorg-android
Source File: OrgFileTest.java
View license
public void testRemoveFileSimple() throws OrgFileNotFoundException {
    OrgFile orgFile = new OrgFile("filename", "name", "checksum");
    orgFile.addFile(resolver);
    OrgFile insertedFile = new OrgFile(orgFile.id, resolver);
    insertedFile.removeFile(resolver);
    Cursor filesCursor = resolver.query(Files.buildIdUri(orgFile.id), Files.DEFAULT_COLUMNS, null, null, null);
    assertEquals(0, filesCursor.getCount());
    filesCursor.close();
    Cursor dataCursor = resolver.query(OrgData.buildIdUri(insertedFile.nodeId), OrgData.DEFAULT_COLUMNS, null, null, null);
    assertEquals(0, dataCursor.getCount());
    dataCursor.close();
}

13. OrgFileTest#testRemoveFileWithNodes()

Project: mobileorg-android
Source File: OrgFileTest.java
View license
public void testRemoveFileWithNodes() throws OrgFileNotFoundException {
    OrgNode node = OrgTestUtils.setupParentScenario(resolver);
    OrgFile orgFile = node.getOrgFile(resolver);
    orgFile.removeFile(resolver);
    Cursor filesCursor = resolver.query(Files.buildIdUri(orgFile.id), Files.DEFAULT_COLUMNS, null, null, null);
    assertEquals(0, filesCursor.getCount());
    filesCursor.close();
    Cursor dataCursor = resolver.query(OrgData.CONTENT_URI, OrgData.DEFAULT_COLUMNS, OrgData.FILE_ID + "=?", new String[] { Long.toString(orgFile.id) }, null);
    assertEquals(0, dataCursor.getCount());
    dataCursor.close();
    OrgTestUtils.cleanupParentScenario(resolver);
}

14. OrgNodeTest#testAddAndUpdateNode()

Project: mobileorg-android
Source File: OrgNodeTest.java
View license
public void testAddAndUpdateNode() throws OrgNodeNotFoundException {
    OrgNode node = OrgTestUtils.getDefaultOrgNode();
    node.write(resolver);
    node.todo = "DONE";
    node.write(resolver);
    Cursor orgDataCursor = resolver.query(OrgData.CONTENT_URI, null, null, null, null);
    assertEquals(1, orgDataCursor.getCount());
    orgDataCursor.close();
    Cursor cursor = resolver.query(OrgData.buildIdUri(node.id), OrgData.DEFAULT_COLUMNS, null, null, null);
    assertNotNull(cursor);
    assertEquals(1, cursor.getCount());
    OrgNode insertedNode = new OrgNode(cursor);
    cursor.close();
    assertTrue(node.equals(insertedNode));
}

15. OrgNodeTest#testArchiveNodeGeneratesEdit()

Project: mobileorg-android
Source File: OrgNodeTest.java
View license
public void testArchiveNodeGeneratesEdit() {
    OrgNode node = OrgTestUtils.getDefaultOrgNode();
    node.write(resolver);
    Cursor editCursor = resolver.query(Edits.CONTENT_URI, Edits.DEFAULT_COLUMNS, null, null, null);
    int baseOfEdits = editCursor.getCount();
    editCursor.close();
    OrgEdit edit = node.archiveNode(resolver);
    edit.type.equals(OrgEdit.TYPE.ARCHIVE);
    Cursor editCursor2 = resolver.query(Edits.CONTENT_URI, Edits.DEFAULT_COLUMNS, null, null, null);
    int numberOfEdits = editCursor2.getCount();
    editCursor2.close();
    assertEquals(baseOfEdits + 1, numberOfEdits);
}

16. OrgNodeTest#testArchiveNodeToSiblingGeneratesEdit()

Project: mobileorg-android
Source File: OrgNodeTest.java
View license
public void testArchiveNodeToSiblingGeneratesEdit() {
    OrgNode node = OrgTestUtils.setupParentScenario(resolver);
    node.write(resolver);
    Cursor editCursor = resolver.query(Edits.CONTENT_URI, Edits.DEFAULT_COLUMNS, null, null, null);
    int baseOfEdits = editCursor.getCount();
    editCursor.close();
    OrgEdit edit = node.archiveNodeToSibling(resolver);
    edit.type.equals(OrgEdit.TYPE.ARCHIVE_SIBLING);
    Cursor editCursor2 = resolver.query(Edits.CONTENT_URI, Edits.DEFAULT_COLUMNS, null, null, null);
    int numberOfEdits = editCursor2.getCount();
    editCursor2.close();
    assertEquals(baseOfEdits + 1, numberOfEdits);
}

17. DBFreshTest#testFreshInstall()

Project: NotePad
Source File: DBFreshTest.java
View license
@SmallTest
public void testFreshInstall() {
    context.deleteDatabase(PREFIX + LegacyDBHelper.LEGACY_DATABASE_NAME);
    context.deleteDatabase(PREFIX + DatabaseHandler.DATABASE_NAME);
    final SQLiteDatabase db = new DatabaseHandler(context, PREFIX).getReadableDatabase();
    // Just open the database, there should be one list and one task present
    Cursor tlc = db.query(TaskList.TABLE_NAME, TaskList.Columns.FIELDS, null, null, null, null, null);
    assertEquals("Should be ONE list present on fresh installs", 1, tlc.getCount());
    tlc.close();
    Cursor tc = db.query(Task.TABLE_NAME, Task.Columns.FIELDS, null, null, null, null, null);
    assertEquals("Should be NO task present on fresh installs", 0, tc.getCount());
    tc.close();
    db.close();
    assertTrue("Could not delete database", context.deleteDatabase(PREFIX + LegacyDBHelper.LEGACY_DATABASE_NAME));
    assertTrue("Could not delete database", context.deleteDatabase(PREFIX + DatabaseHandler.DATABASE_NAME));
}

18. WayPointsOverlay#refresh()

View license
public void refresh() {
    wayPointItems.clear();
    Cursor c = this.pContentResolver.query(TrackContentProvider.waypointsUri(trackId), null, null, null, TrackContentProvider.Schema.COL_TIMESTAMP + " asc");
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        OverlayItem i = new OverlayItem(c.getString(c.getColumnIndex(Schema.COL_NAME)), c.getString(c.getColumnIndex(Schema.COL_NAME)), new GeoPoint(c.getDouble(c.getColumnIndex(Schema.COL_LATITUDE)), c.getDouble(c.getColumnIndex(Schema.COL_LONGITUDE))));
        wayPointItems.add(i);
    }
    c.close();
    populate();
}

19. LibraryDatabaseHelper#getKeys()

View license
private List<String> getKeys(Field fieldName, Order order) {
    String[] keyField = { fieldName.toString() };
    Cursor fieldCursor = getDataBase().query(LIB_BOOKS_TABLE, keyField, null, new String[0], null, null, fieldName != null ? "LOWER(" + fieldName.toString() + ") " + order.toString() : null);
    List<String> keys = new ArrayList<String>();
    fieldCursor.moveToFirst();
    fieldCursor.moveToFirst();
    while (!fieldCursor.isAfterLast()) {
        keys.add(fieldCursor.getString(0));
        fieldCursor.moveToNext();
    }
    fieldCursor.close();
    return keys;
}

20. SQLiteDatabaseTest#testExecSQLInsertNullShouldBeException()

Project: robolectric
Source File: SQLiteDatabaseTest.java
View license
@Test(expected = Exception.class)
public void testExecSQLInsertNullShouldBeException() throws Exception {
    //this inserts null in android, but it when it happens it is likely an error.  H2 throws an exception.  So we'll make Robolectric expect an Exception so that the error can be found.
    database.delete("exectable", null, null);
    Cursor cursor = database.rawQuery("select * from exectable", null);
    cursor.moveToFirst();
    assertThat(cursor.getCount(), equalTo(0));
    database.execSQL("insert into exectable (first_column) values (?);", new String[] {});
    Cursor cursor2 = database.rawQuery("select * from exectable", new String[] { null });
    cursor.moveToFirst();
    assertThat(cursor2.getCount(), equalTo(1));
}

21. PurchaseDataSource#getEntitlementRecordByReceiptId()

Project: SeriesGuide
Source File: PurchaseDataSource.java
View license
/**
     * Find entitlement record by specified receipt ID.
     */
@Nullable
public PurchaseRecord getEntitlementRecordByReceiptId(final String receiptId) {
    Timber.d("getEntitlementRecordByReceiptId: receiptId (%s)", receiptId);
    final String where = AmazonBillingSQLiteHelper.COLUMN_RECEIPT_ID + "= ?";
    final Cursor cursor = database.query(AmazonBillingSQLiteHelper.TABLE_PURCHASES, allColumns, where, new String[] { receiptId }, null, null, null);
    final PurchaseRecord result;
    cursor.moveToFirst();
    if (cursor.isAfterLast()) {
        result = null;
        Timber.d("getEntitlementRecordByReceiptId: no record found ");
    } else {
        result = cursorToPurchaseRecord(cursor);
        Timber.d("getEntitlementRecordByReceiptId: found ");
    }
    cursor.close();
    return result;
}

22. PurchaseDataSource#getLatestEntitlementRecordBySku()

Project: SeriesGuide
Source File: PurchaseDataSource.java
View license
/**
     * Return the entitlement for given user and sku.
     */
@Nullable
public PurchaseRecord getLatestEntitlementRecordBySku(String userId, String sku) {
    Timber.d("getEntitlementRecordBySku: userId (%s), sku (%s)", userId, sku);
    final String where = AmazonBillingSQLiteHelper.COLUMN_USER_ID + " = ? and " + AmazonBillingSQLiteHelper.COLUMN_SKU + " = ?";
    final Cursor cursor = database.query(AmazonBillingSQLiteHelper.TABLE_PURCHASES, allColumns, where, new String[] { userId, sku }, null, null, AmazonBillingSQLiteHelper.COLUMN_DATE_FROM + " desc ");
    final PurchaseRecord result;
    cursor.moveToFirst();
    if (cursor.isAfterLast()) {
        result = null;
        Timber.d("getEntitlementRecordBySku: no record found ");
    } else {
        result = cursorToPurchaseRecord(cursor);
        Timber.d("getEntitlementRecordBySku: found ");
    }
    cursor.close();
    return result;
}

23. TaskRecorder#getInfoByID()

View license
private String getInfoByID(int id, String KEY) {
    db = mSQLHelper.getReadableDatabase();
    String selection = KEY_ID + "=?";
    String[] selectionArgs = { String.valueOf(id) };
    Cursor cursor = db.query(TASKS_TABLE_NAME, null, selection, selectionArgs, null, null, null);
    int index = cursor.getColumnIndex(KEY);
    if (cursor.getCount() == 0) {
        return "0";
    }
    ArrayList<String> list = new ArrayList<String>();
    for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
        if (KEY.equals(KEY_COMPLETED) || KEY.equals(KEY_DELETED)) {
            list.add(String.valueOf(cursor.getInt(index)));
        } else {
            list.add(cursor.getString(index));
        }
    }
    cursor.close();
    return list.get(0);
}

24. DatabaseCursorTest#testRequery()

View license
@MediumTest
public void testRequery() throws Exception {
    populateDefaultTable();
    Cursor c = mDatabase.rawQuery("SELECT * FROM test", null);
    assertNotNull(c);
    assertEquals(3, c.getCount());
    c.deactivate();
    c.requery();
    assertEquals(3, c.getCount());
    c.close();
}

25. DatabaseCursorTest#testRequeryWithSelection()

View license
@MediumTest
public void testRequeryWithSelection() throws Exception {
    populateDefaultTable();
    Cursor c = mDatabase.rawQuery("SELECT data FROM test WHERE data = '" + sString1 + "'", null);
    assertNotNull(c);
    assertEquals(1, c.getCount());
    assertTrue(c.moveToFirst());
    assertEquals(sString1, c.getString(0));
    c.deactivate();
    c.requery();
    assertEquals(1, c.getCount());
    assertTrue(c.moveToFirst());
    assertEquals(sString1, c.getString(0));
    c.close();
}

26. DatabaseCursorTest#testRequeryWithSelectionArgs()

View license
@MediumTest
public void testRequeryWithSelectionArgs() throws Exception {
    populateDefaultTable();
    Cursor c = mDatabase.rawQuery("SELECT data FROM test WHERE data = ?", new String[] { sString1 });
    assertNotNull(c);
    assertEquals(1, c.getCount());
    assertTrue(c.moveToFirst());
    assertEquals(sString1, c.getString(0));
    c.deactivate();
    c.requery();
    assertEquals(1, c.getCount());
    assertTrue(c.moveToFirst());
    assertEquals(sString1, c.getString(0));
    c.close();
}

27. DeleteTest#deleteOne()

Project: storio
Source File: DeleteTest.java
View license
@Test
public void deleteOne() {
    final User user = putUserBlocking();
    final Cursor cursorAfterInsert = db.query(UserTableMeta.TABLE, null, null, null, null, null, null);
    assertThat(cursorAfterInsert.getCount()).isEqualTo(1);
    cursorAfterInsert.close();
    deleteUserBlocking(user);
    final Cursor cursorAfterDelete = db.query(UserTableMeta.TABLE, null, null, null, null, null, null);
    assertThat(cursorAfterDelete.getCount()).isEqualTo(0);
    cursorAfterDelete.close();
}

28. DB#getUser()

Project: AcFun-Area63
Source File: DB.java
View license
public User getUser() {
    SQLiteDatabase db = helper.getReadableDatabase();
    Cursor query = db.rawQuery("SELECT * FROM " + DBOpenHelper.TABLE_USER, null);
    User user = null;
    if (query.moveToFirst()) {
        user = new User();
        user.id = query.getInt(query.getColumnIndex("uid"));
        user.name = query.getString(query.getColumnIndex("name"));
        user.avatar = query.getString(query.getColumnIndex("avatar"));
        user.signature = query.getString(query.getColumnIndex("signature"));
        user.cookies = query.getString(query.getColumnIndex("cookies"));
        user.savedTime = query.getLong(query.getColumnIndex("time"));
    }
    query.close();
    db.close();
    return user;
}

29. DB#getFavList()

Project: AcFun-Area63
Source File: DB.java
View license
public List<Content> getFavList() {
    SQLiteDatabase db = helper.getReadableDatabase();
    Cursor query = db.rawQuery("SELECT * FROM " + DBOpenHelper.TABLE_FAV, null);
    if (query.getCount() <= 0) {
        query.close();
        db.close();
        return null;
    }
    List<Content> cs = new ArrayList<Content>(query.getCount());
    while (query.moveToNext()) {
        Content c = new Content();
        c.aid = query.getInt(query.getColumnIndex("aid"));
        c.title = query.getString(query.getColumnIndex("title"));
        c.description = query.getString(query.getColumnIndex("description"));
        c.channelId = query.getInt(query.getColumnIndex("channelId"));
        c.stows = query.getInt(query.getColumnIndex("stows"));
        c.releaseDate = query.getLong(query.getColumnIndex("time"));
        cs.add(c);
    }
    query.close();
    db.close();
    return cs;
}

30. HistoryDatabase#getHistory()

Project: actor-platform
Source File: HistoryDatabase.java
View license
public static ArrayList<String> getHistory(Context context) {
    ArrayList<String> history = new ArrayList<String>();
    SQLiteDatabase database = new HistoryDatabase(context).getWritableDatabase();
    Cursor cursor = database.query(SELECTED_HISTORY_TABLE, SELECTED_HISTORY_COLUMNS, null, null, null, null, "last_selected DESC");
    int pathColumnIndex = cursor.getColumnIndex("path");
    ArrayList<String> removeIndexes = new ArrayList<String>();
    if (cursor.moveToFirst()) {
        int count = 0;
        do {
            if (count < 20) {
                count++;
                history.add(cursor.getString(pathColumnIndex));
            } else {
                removeIndexes.add(cursor.getString(pathColumnIndex));
            }
        } while (cursor.moveToNext());
    }
    cursor.close();
    String[] removeIndexesArray = new String[removeIndexes.size()];
    database.delete(SELECTED_HISTORY_TABLE, "path = ?", removeIndexes.toArray(removeIndexesArray));
    database.close();
    return history;
}

31. WeatherMuzeiSource#onUpdate()

View license
@Override
protected void onUpdate(int reason) {
    String location = Utility.getPreferredLocation(this);
    Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(location, System.currentTimeMillis());
    Cursor cursor = getContentResolver().query(weatherForLocationUri, FORECAST_COLUMNS, null, null, WeatherContract.WeatherEntry.COLUMN_DATE + " ASC");
    if (cursor.moveToFirst()) {
        int weatherId = cursor.getInt(INDEX_WEATHER_ID);
        String desc = cursor.getString(INDEX_SHORT_DESC);
        String imageUrl = Utility.getImageUrlForWeatherCondition(weatherId);
        // Only publish a new wallpaper if we have a valid image
        if (imageUrl != null) {
            publishArtwork(new Artwork.Builder().imageUri(Uri.parse(imageUrl)).title(desc).byline(location).viewIntent(new Intent(this, MainActivity.class)).build());
        }
    }
    cursor.close();
}

32. SmsManager#execSqlRetInt()

Project: alertsystem
Source File: SmsManager.java
View license
public static int execSqlRetInt(String sql) {
    int ret = -1;
    SQLiteDatabase db = mAlertSystemDBHelper.getReadableDatabase();
    // ShowLog(sql);
    Cursor result = db.rawQuery(sql, null);
    result.moveToFirst();
    while (!result.isAfterLast()) {
        ret = result.getInt(0);
        break;
    }
    result.close();
    return ret;
}

33. Utils#getRealPathFromURI()

Project: Alexei
Source File: Utils.java
View license
public String getRealPathFromURI(Context context, Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    //This method was deprecated in API level 11
    //Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    CursorLoader cursorLoader = new CursorLoader(context, contentUri, proj, null, null, null);
    Cursor cursor = cursorLoader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

34. MediaStoreHack#getUriFromFile()

View license
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;
    }
}

35. HistoryManager#readTable()

View license
public ArrayList<String> readTable(String table) {
    Cursor c = db.rawQuery("SELECT * FROM " + table, null);
    c.moveToLast();
    ArrayList<String> paths = new ArrayList<String>();
    do {
        try {
            paths.add(c.getString(c.getColumnIndex("PATH")));
        } catch (Exception e) {
        }
    } while (c.moveToPrevious());
    return paths;
}

36. HistoryManager#readTableSecondary()

View license
public ArrayList<String[]> readTableSecondary(String table) {
    Cursor c = db.rawQuery("SELECT * FROM " + table, null);
    c.moveToLast();
    ArrayList<String[]> paths = new ArrayList<String[]>();
    do {
        try {
            paths.add(new String[] { c.getString(c.getColumnIndex("NAME")), c.getString(c.getColumnIndex("PATH")) });
        } catch (Exception e) {
        }
    } while (c.moveToPrevious());
    return paths;
}

37. FileDataStorageManager#getFileByPath()

Project: android
Source File: FileDataStorageManager.java
View license
public OCFile getFileByPath(String path) {
    Cursor c = getFileCursorForValue(ProviderTableMeta.FILE_PATH, path);
    OCFile file = null;
    if (c.moveToFirst()) {
        file = createFileInstance(c);
    }
    c.close();
    if (file == null && OCFile.ROOT_PATH.equals(path)) {
        // root should always exist
        return createRootDir();
    }
    return file;
}

38. FileDataStorageManager#getCapability()

Project: android
Source File: FileDataStorageManager.java
View license
public OCCapability getCapability(String accountName) {
    OCCapability capability = null;
    Cursor c = getCapabilityCursorForAccount(accountName);
    if (c.moveToFirst()) {
        capability = createCapabilityInstance(c);
    } else {
        // return default with all UNKNOWN
        capability = new OCCapability();
    }
    c.close();
    return capability;
}

39. UploadsStorageManager#getUploads()

Project: android
Source File: UploadsStorageManager.java
View license
private OCUpload[] getUploads(String selection, String[] selectionArgs) {
    Cursor c = getDB().query(ProviderTableMeta.CONTENT_URI_UPLOADS, null, selection, selectionArgs, null);
    OCUpload[] list = new OCUpload[c.getCount()];
    if (c.moveToFirst()) {
        do {
            OCUpload upload = createOCUploadFromCursor(c);
            if (upload == null) {
                Log_OC.e(TAG, "OCUpload could not be created from cursor");
            } else {
                list[c.getPosition()] = upload;
            }
        } while (c.moveToNext());
    }
    c.close();
    return list;
}

40. ChunksDataSource#chunksRelatedTask()

View license
public List<Chunk> chunksRelatedTask(int taskID) {
    List<Chunk> chunks = new ArrayList<Chunk>();
    String query = "SELECT * FROM " + TABLES.CHUNKS + " WHERE " + CHUNKS.COLUMN_TASK_ID + " == " + taskID;
    Cursor cr = database.rawQuery(query, null);
    if (cr.moveToFirst()) {
        do {
            Chunk chunk = new Chunk(taskID);
            chunk.cursorToChunk(cr);
            chunks.add(chunk);
        } while (cr.moveToNext());
    }
    cr.close();
    return chunks;
}

41. TasksDataSource#getTaskInfo()

View license
public Task getTaskInfo(int id) {
    String query = "SELECT * FROM " + TABLES.TASKS + " WHERE " + TASKS.COLUMN_ID + "=" + SqlString.Int(id);
    Cursor cr = database.rawQuery(query, null);
    Log.d("--------", "raw query");
    Task task = new Task();
    if (cr.moveToFirst()) {
        task.cursorToTask(cr);
    }
    cr.close();
    Log.d("--------", "cr close");
    return task;
}

42. PickContactActivity#showInfo()

View license
private void showInfo(Uri contact) {
    String[] projection;
    if (isSupportsContactsV2()) {
        projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME };
    } else {
        projection = new String[] { Contacts.People.DISPLAY_NAME };
    }
    Cursor cursor = getContentResolver().query(contact, projection, null, null, null);
    cursor.moveToFirst();
    String name;
    if (isSupportsContactsV2()) {
        name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    } else {
        name = cursor.getString(cursor.getColumnIndex(Contacts.People.DISPLAY_NAME));
    }
    cursor.close();
    infoView.setText(name);
}

43. TestOrmLiteSimpleProvider#testOnQuery()

View license
public void testOnQuery() {
    // given
    Account account1 = new Account(TEST_NAME_1);
    Account account2 = new Account(TEST_NAME_2);
    RuntimeExceptionDao<Account, Integer> simpleDao = getHelper().getRuntimeExceptionDao(Account.class);
    simpleDao.create(account1);
    simpleDao.create(account2);
    List<Account> accountList = simpleDao.queryForAll();
    assertEquals(2, accountList.size());
    // when
    Cursor cursor = this.resolver.query(AccountContract.CONTENT_URI, new String[] { BaseColumns._ID, AccountContract.NAME }, null, null, null);
    accountList = new ArrayList<Account>();
    while (cursor.moveToNext()) {
        Account account = new Account(cursor.getString(1));
        accountList.add(account);
    }
    cursor.close();
    // then
    assertEquals(2, accountList.size());
    assertEquals(TEST_NAME_1, accountList.get(0).getName());
    assertEquals(TEST_NAME_2, accountList.get(1).getName());
}

44. TestOrmLiteSimpleProvider#testOnQueryWithOrder()

View license
public void testOnQueryWithOrder() {
    // given
    Account account1 = new Account(TEST_NAME_1);
    Account account2 = new Account(TEST_NAME_2);
    RuntimeExceptionDao<Account, Integer> simpleDao = getHelper().getRuntimeExceptionDao(Account.class);
    simpleDao.create(account1);
    simpleDao.create(account2);
    List<Account> accountList = simpleDao.queryForAll();
    assertEquals(2, accountList.size());
    // when
    String order = BaseColumns._ID + " DESC";
    Cursor cursor = this.resolver.query(AccountContract.CONTENT_URI, new String[] { BaseColumns._ID, AccountContract.NAME }, null, null, order);
    accountList = new ArrayList<Account>();
    while (cursor.moveToNext()) {
        Account account = new Account(cursor.getString(1));
        accountList.add(account);
    }
    cursor.close();
    // then
    assertEquals(2, accountList.size());
    assertEquals(TEST_NAME_2, accountList.get(0).getName());
    assertEquals(TEST_NAME_1, accountList.get(1).getName());
}

45. DataSource#findWifiAp()

Project: android-proxy
Source File: DataSource.java
View license
public long findWifiAp(APLNetworkId aplNetworkId) {
    App.getTraceUtils().startTrace(TAG, "findWifiAp", Log.DEBUG);
    SQLiteDatabase database = DatabaseSQLiteOpenHelper.getInstance(context).getReadableDatabase();
    String query = "SELECT " + DatabaseSQLiteOpenHelper.COLUMN_ID + " FROM " + DatabaseSQLiteOpenHelper.TABLE_WIFI_AP + " WHERE " + DatabaseSQLiteOpenHelper.COLUMN_WIFI_SSID + " =?" + " AND " + DatabaseSQLiteOpenHelper.COLUMN_WIFI_SECURITY_TYPE + "=?";
    String[] selectionArgs = { aplNetworkId.SSID, aplNetworkId.Security.toString() };
    Cursor cursor = DBUtils.rawQuery(database, query, selectionArgs);
    cursor.moveToFirst();
    long wifiId = -1;
    if (!cursor.isAfterLast()) {
        wifiId = cursor.getLong(0);
    }
    cursor.close();
    App.getTraceUtils().stopTrace(TAG, "findWifiAp", String.format("Found Wi-Fi Id: '%d'", wifiId), Log.DEBUG);
    return wifiId;
}

46. DataSource#findPac()

Project: android-proxy
Source File: DataSource.java
View license
public long findPac(PacEntity pacEntity) {
    App.getTraceUtils().startTrace(TAG, "findPac", Log.DEBUG);
    SQLiteDatabase database = DatabaseSQLiteOpenHelper.getInstance(context).getReadableDatabase();
    String query = "SELECT " + DatabaseSQLiteOpenHelper.COLUMN_ID + " FROM " + DatabaseSQLiteOpenHelper.TABLE_PAC + " WHERE " + DatabaseSQLiteOpenHelper.COLUMN_PAC_URL_FILE + " =?";
    String[] selectionArgs = { pacEntity.getPacUriFile().toString() };
    Cursor cursor = DBUtils.rawQuery(database, query, selectionArgs);
    cursor.moveToFirst();
    long pacId = -1;
    if (!cursor.isAfterLast()) {
        pacId = cursor.getLong(0);
    }
    cursor.close();
    App.getTraceUtils().stopTrace(TAG, "findPac", String.format("Found PAC Id: '%d'", pacId), Log.DEBUG);
    return pacId;
}

47. DataSource#findTag()

Project: android-proxy
Source File: DataSource.java
View license
public long findTag(String tagName) {
    App.getTraceUtils().startTrace(TAG, "findTag", Log.DEBUG);
    SQLiteDatabase database = DatabaseSQLiteOpenHelper.getInstance(context).getReadableDatabase();
    String query = "SELECT " + DatabaseSQLiteOpenHelper.COLUMN_ID + " FROM " + DatabaseSQLiteOpenHelper.TABLE_TAGS + " WHERE " + DatabaseSQLiteOpenHelper.COLUMN_TAG + " =?";
    Cursor cursor = DBUtils.rawQuery(database, query, new String[] { tagName });
    cursor.moveToFirst();
    long tagId = -1;
    if (!cursor.isAfterLast()) {
        tagId = cursor.getLong(0);
    }
    cursor.close();
    App.getTraceUtils().stopTrace(TAG, "findTag", String.format("Found TAG Id: '%d'", tagId), Log.DEBUG);
    return tagId;
}

48. DataSource#getTagsCount()

Project: android-proxy
Source File: DataSource.java
View license
public long getTagsCount() {
    SQLiteDatabase database = DatabaseSQLiteOpenHelper.getInstance(context).getReadableDatabase();
    String query = "SELECT COUNT(1)" + " FROM " + DatabaseSQLiteOpenHelper.TABLE_TAGS;
    Cursor cursor = DBUtils.rawQuery(database, query, null);
    cursor.moveToFirst();
    long result = cursor.getLong(0);
    // Make sure to close the cursor
    cursor.close();
    return result;
}

49. DataSource#getAllPac()

Project: android-proxy
Source File: DataSource.java
View license
public Map<Long, PacEntity> getAllPac() {
    SQLiteDatabase database = DatabaseSQLiteOpenHelper.getInstance(context).getReadableDatabase();
    Map<Long, PacEntity> pacs = new HashMap<Long, PacEntity>();
    Cursor cursor = database.query(DatabaseSQLiteOpenHelper.TABLE_PAC, DatabaseSQLiteOpenHelper.TABLE_PAC_COLUMNS, null, null, null, null, DatabaseSQLiteOpenHelper.COLUMN_PAC_URL_FILE + " ASC");
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        PacEntity pacEntity = cursorToPAC(cursor);
        pacs.put(pacEntity.getId(), pacEntity);
        cursor.moveToNext();
    }
    cursor.close();
    return pacs;
}

50. DataSource#getAllTags()

Project: android-proxy
Source File: DataSource.java
View license
public List<TagEntity> getAllTags() {
    SQLiteDatabase database = DatabaseSQLiteOpenHelper.getInstance(context).getReadableDatabase();
    List<TagEntity> proxies = new ArrayList<TagEntity>();
    Cursor cursor = database.query(DatabaseSQLiteOpenHelper.TABLE_TAGS, DatabaseSQLiteOpenHelper.TABLE_TAGS_COLUMNS, null, null, null, null, DatabaseSQLiteOpenHelper.COLUMN_TAG + " ASC");
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        TagEntity proxy = cursorToTag(cursor);
        proxies.add(proxy);
        cursor.moveToNext();
    }
    cursor.close();
    return proxies;
}

51. DataSource#getProxyTagLinkForProxy()

Project: android-proxy
Source File: DataSource.java
View license
private List<ProxyTagLinkEntity> getProxyTagLinkForProxy(long proxyId) {
    SQLiteDatabase database = DatabaseSQLiteOpenHelper.getInstance(context).getReadableDatabase();
    String query = "SELECT " + DatabaseSQLiteOpenHelper.TABLE_TAGGED_PROXIES_COLUMNS_STRING + " FROM " + DatabaseSQLiteOpenHelper.TABLE_PROXY_TAG_LINKS + " WHERE " + DatabaseSQLiteOpenHelper.COLUMN_PROXY_ID + " =?";
    Cursor cursor = DBUtils.rawQuery(database, query, new String[] { String.valueOf(proxyId) });
    cursor.moveToFirst();
    List<ProxyTagLinkEntity> links = new ArrayList<ProxyTagLinkEntity>();
    while (!cursor.isAfterLast()) {
        ProxyTagLinkEntity link = cursorToProxyTagLink(cursor);
        links.add(link);
        cursor.moveToNext();
    }
    cursor.close();
    return links;
}

52. MyDatabase#getUpgradeVersion()

View license
public int getUpgradeVersion() {
    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    String[] sqlSelect = { "MAX (version)" };
    String sqlTables = "upgrades";
    qb.setTables(sqlTables);
    Cursor c = qb.query(db, sqlSelect, null, null, null, null, null);
    int v = 0;
    c.moveToFirst();
    if (!c.isAfterLast()) {
        v = c.getInt(0);
    }
    c.close();
    return v;
}

53. RingtoneManagerCompat#getCursor()

View license
@Override
public Cursor getCursor() {
    Cursor mCursor = getCursorInternal();
    if (mCursor != null && mCursor.requery()) {
        return mCursor;
    }
    final Cursor internalCursor = getInternalRingtones();
    final Cursor mediaCursor = getMediaRingtones();
    mCursor = new SortCursor(new Cursor[] { internalCursor, mediaCursor }, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
    setCursorInternal(mCursor);
    return mCursor;
}

54. PlayersDBHelper#findPlayerByPackageName()

View license
public synchronized Player findPlayerByPackageName(String packageName) {
    final Cursor cursor = AppDBManager.getInstance(context).getReadableDatabase().query(TableInfo.TABLE_NAME, null, TableInfo.COLUMN_PACKAGE_NAME + " = ?", new String[] { packageName }, null, null, TableInfo.COLUMN_ID);
    Player player = null;
    if (cursor.moveToFirst()) {
        player = parseFromCursor(cursor);
    }
    cursor.close();
    return player;
}

55. PlayersDBHelper#getAll()

View license
public synchronized List<Player> getAll() {
    final Cursor cursor = AppDBManager.getInstance(context).getReadableDatabase().query(TableInfo.TABLE_NAME, null, null, null, null, null, TableInfo.COLUMN_ID);
    final List<Player> players = new ArrayList<Player>(cursor.getCount());
    if (cursor.moveToFirst()) {
        do {
            players.add(parseFromCursor(cursor));
        } while (cursor.moveToNext());
    }
    cursor.close();
    return players;
}

56. TracksDBHelper#getLastAddedTrack()

View license
public synchronized Track getLastAddedTrack() {
    Cursor cursor = AppDBManager.getInstance(context).getReadableDatabase().rawQuery("SELECT * FROM " + TableInfo.TABLE_NAME + " ORDER BY " + TableInfo.COLUMN_INTERNAL_ID + " DESC LIMIT 1", null);
    Track lastAddedTrack = null;
    if (cursor.moveToFirst()) {
        lastAddedTrack = parseFromCursor(cursor);
    }
    cursor.close();
    return lastAddedTrack;
}

57. MessagesProviderTest#testEmptyPeer()

View license
/** Tries to reproduce issue #761. */
@Test
public void testEmptyPeer() {
    // from MessagingNotification
    String query = MyMessages.CommonColumns.NEW + " <> 0 AND " + MyMessages.CommonColumns.DIRECTION + " = " + Messages.DIRECTION_IN + " AND " + MyMessages.CommonColumns.PEER + " <> ? AND " + Groups.GROUP_JID + " <> ?";
    String[] args = { "", "" };
    Cursor c = getMockContentResolver().query(Threads.CONTENT_URI, null, query, args, null);
    assertNotNull(c);
    c.close();
    args = new String[] { "   ", "       " };
    c = getMockContentResolver().query(Threads.CONTENT_URI, null, query, args, null);
    assertNotNull(c);
    c.close();
}

58. KontalkGroupCommands#isGroupCreatedSent()

View license
/** Returns true if the create group command for the given thread has been sent. */
public static boolean isGroupCreatedSent(Context context, long threadId) {
    Cursor c = context.getContentResolver().query(MyMessages.Messages.CONTENT_URI, new String[] { MyMessages.Messages.STATUS }, MyMessages.Messages.THREAD_ID + "=" + threadId + " AND " + MyMessages.Messages.DIRECTION + "=" + MyMessages.Messages.DIRECTION_OUT + " AND " + MyMessages.Messages.BODY_MIME + "=? AND " + MyMessages.Messages.BODY_CONTENT + " LIKE ?", new String[] { GroupCommandComponent.MIME_TYPE, GroupCommandComponent.COMMAND_CREATE + ":%" }, null);
    if (c.moveToNext()) {
        int status = c.getInt(0);
        return status == MyMessages.Messages.STATUS_SENT || status == MyMessages.Messages.STATUS_RECEIVED;
    }
    c.close();
    return false;
}

59. MessagesProviderUtils#getGroupMembers()

View license
public static String[] getGroupMembers(Context context, String groupJid, int flags) {
    Cursor c = context.getContentResolver().query(Groups.getMembersUri(groupJid), new String[] { Groups.PEER }, // handle zero flags special case (means all flags cleared)
    flags != 0 ? "(" + Groups.PENDING + " & " + flags + ") = " + flags : Groups.PENDING + "=0", null, null);
    String[] members = new String[c.getCount()];
    int i = 0;
    while (c.moveToNext()) {
        members[i++] = c.getString(0);
    }
    c.close();
    return members;
}

60. UsersProvider#getPublicKey()

Project: androidclient
Source File: UsersProvider.java
View license
/** Retrieves the (un)trusted public key for a user. */
public static PGPPublicKeyRing getPublicKey(Context context, String jid, boolean trusted) {
    byte[] keydata = null;
    ContentResolver res = context.getContentResolver();
    Cursor c = res.query(Users.CONTENT_URI.buildUpon().appendPath(jid).build(), new String[] { trusted ? Keys.TRUSTED_PUBLIC_KEY : Users.PUBLIC_KEY }, null, null, null);
    if (c.moveToFirst())
        keydata = c.getBlob(0);
    c.close();
    try {
        return PGP.readPublicKeyring(keydata);
    } catch (Exception e) {
    }
    return null;
}

61. UsersProvider#getPublicKeyInternal()

Project: androidclient
Source File: UsersProvider.java
View license
/** Retrieves a public key directly from the keys table. */
public static PGPPublicKeyRing getPublicKeyInternal(Context context, String jid) {
    byte[] keydata = null;
    ContentResolver res = context.getContentResolver();
    Cursor c = res.query(Keys.CONTENT_URI.buildUpon().appendPath(jid).build(), new String[] { Keys.PUBLIC_KEY }, null, null, null);
    if (c.moveToFirst())
        keydata = c.getBlob(0);
    c.close();
    try {
        return PGP.readPublicKeyring(keydata);
    } catch (Exception e) {
    }
    return null;
}

62. UsersProvider#getFingerprint()

Project: androidclient
Source File: UsersProvider.java
View license
/** Retrieves the (un)trusted fingerprint for a user. */
public static String getFingerprint(Context context, String jid, boolean trusted) {
    String fingerprint = null;
    ContentResolver res = context.getContentResolver();
    Cursor c = res.query(Users.CONTENT_URI.buildUpon().appendPath(jid).build(), new String[] { trusted ? Keys.TRUSTED_FINGERPRINT : Users.FINGERPRINT }, null, null, null);
    if (c.moveToFirst())
        fingerprint = c.getString(0);
    c.close();
    return fingerprint;
}

63. UsersProvider#getLastSeen()

Project: androidclient
Source File: UsersProvider.java
View license
/** Retrieves the last seen timestamp for a user. */
public static long getLastSeen(Context context, String jid) {
    long timestamp = -1;
    ContentResolver res = context.getContentResolver();
    Cursor c = res.query(Users.CONTENT_URI.buildUpon().appendPath(jid).build(), new String[] { Users.LAST_SEEN }, null, null, null);
    if (c.moveToFirst())
        timestamp = c.getLong(0);
    c.close();
    return timestamp;
}

64. UsersProvider#getTrustedKeys()

Project: androidclient
Source File: UsersProvider.java
View license
/** Returns a JID-fingerprint map of trusted keys. */
public static Map<String, String> getTrustedKeys(Context context) {
    Cursor c = context.getContentResolver().query(Keys.CONTENT_URI, new String[] { Keys.JID, Keys.FINGERPRINT }, Keys.FINGERPRINT + " IS NOT NULL", null, null);
    Map<String, String> list = new HashMap<>(c.getCount());
    while (c.moveToNext()) {
        list.put(c.getString(0), c.getString(1));
    }
    c.close();
    return list;
}

65. ItemsDataHelper#query()

View license
@Override
public DemoItem query(String id) {
    DemoItem item = null;
    Cursor cursor;
    cursor = query(null, ItemsDBInfo.ID + "= ?", new String[] { id }, null);
    if (cursor.moveToFirst()) {
        item = DemoItem.fromCursor(cursor);
    }
    cursor.close();
    return item;
}

66. TagsManager#getTags()

Project: AndroidTagGroup
Source File: TagsManager.java
View license
public String[] getTags() {
    List<String> tagList = new ArrayList<>();
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor c = db.query(TagsTable.TABLE_NAME, new String[] { TagsTable.TAG }, null, null, null, null, null);
    while (c.moveToNext()) {
        String tag = c.getString(c.getColumnIndex(TagsTable.TAG));
        tagList.add(tag);
    }
    c.close();
    db.close();
    return tagList.toArray(new String[] {});
}

67. FavoriteDao#read()

Project: AndroidWeekly
Source File: FavoriteDao.java
View license
public List<Favorite> read() {
    List<Favorite> favorites = new ArrayList<>();
    Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM FAVORITE ORDER BY TIME DESC", null);
    while (cursor.moveToNext()) {
        Article article = new Article();
        article.setTitle(cursor.getString(INDEX_TITLE));
        article.setBrief(cursor.getString(INDEX_BRIEF));
        article.setLink(cursor.getString(INDEX_LINK));
        article.setImageUrl(cursor.getString(INDEX_IMAGE_URL));
        article.setDomain(cursor.getString(INDEX_DOMAIN));
        article.setIssue(cursor.getString(INDEX_ISSUE));
        article.setSection(cursor.getString(INDEX_SECTION));
        Favorite favorite = new Favorite(article);
        favorite.setTime(cursor.getLong(INDEX_TIME));
        favorites.add(favorite);
    }
    cursor.close();
    return favorites;
}

68. DBReader#getFeedList()

Project: AntennaPod
Source File: DBReader.java
View license
private static List<Feed> getFeedList(PodDBAdapter adapter) {
    Cursor feedlistCursor = adapter.getAllFeedsCursor();
    List<Feed> feeds = new ArrayList<>(feedlistCursor.getCount());
    if (feedlistCursor.moveToFirst()) {
        do {
            Feed feed = extractFeedFromCursorRow(adapter, feedlistCursor);
            feeds.add(feed);
        } while (feedlistCursor.moveToNext());
    }
    feedlistCursor.close();
    return feeds;
}

69. DBReader#getFeedListDownloadUrls()

Project: AntennaPod
Source File: DBReader.java
View license
/**
     * Returns a list with the download URLs of all feeds.
     *
     * @return A list of Strings with the download URLs of all feeds.
     */
public static List<String> getFeedListDownloadUrls() {
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    List<String> result = new ArrayList<>();
    adapter.open();
    Cursor feeds = adapter.getFeedCursorDownloadUrls();
    if (feeds.moveToFirst()) {
        do {
            result.add(feeds.getString(1));
        } while (feeds.moveToNext());
    }
    feeds.close();
    adapter.close();
    return result;
}

70. DBReader#getQueueIDList()

Project: AntennaPod
Source File: DBReader.java
View license
static LongList getQueueIDList(PodDBAdapter adapter) {
    Cursor queueCursor = adapter.getQueueIDCursor();
    LongList queueIds = new LongList(queueCursor.getCount());
    if (queueCursor.moveToFirst()) {
        do {
            queueIds.add(queueCursor.getLong(0));
        } while (queueCursor.moveToNext());
    }
    queueCursor.close();
    return queueIds;
}

71. DBReader#getFavoriteIDList()

Project: AntennaPod
Source File: DBReader.java
View license
public static LongList getFavoriteIDList() {
    Log.d(TAG, "getFavoriteIDList() called");
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    Cursor favoritesCursor = adapter.getFavoritesCursor();
    LongList favoriteIDs = new LongList(favoritesCursor.getCount());
    if (favoritesCursor.moveToFirst()) {
        do {
            favoriteIDs.add(favoritesCursor.getLong(0));
        } while (favoritesCursor.moveToNext());
    }
    favoritesCursor.close();
    adapter.close();
    return favoriteIDs;
}

72. DBReader#getDownloadLog()

Project: AntennaPod
Source File: DBReader.java
View license
/**
     * Loads the download log from the database.
     *
     * @return A list with DownloadStatus objects that represent the download log.
     * The size of the returned list is limited by {@link #DOWNLOAD_LOG_SIZE}.
     */
public static List<DownloadStatus> getDownloadLog() {
    Log.d(TAG, "getDownloadLog() called");
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    Cursor logCursor = adapter.getDownloadLogCursor(DOWNLOAD_LOG_SIZE);
    List<DownloadStatus> downloadLog = new ArrayList<>(logCursor.getCount());
    if (logCursor.moveToFirst()) {
        do {
            DownloadStatus status = DownloadStatus.fromCursor(logCursor);
            downloadLog.add(status);
        } while (logCursor.moveToNext());
    }
    logCursor.close();
    adapter.close();
    Collections.sort(downloadLog, new DownloadStatusComparator());
    return downloadLog;
}

73. DBReader#getFeedDownloadLog()

Project: AntennaPod
Source File: DBReader.java
View license
/**
     * Loads the download log for a particular feed from the database.
     *
     * @param feed Feed for which the download log is loaded
     * @return A list with DownloadStatus objects that represent the feed's download log,
     *         newest events first.
     */
public static List<DownloadStatus> getFeedDownloadLog(Feed feed) {
    Log.d(TAG, "getFeedDownloadLog() called with: " + "feed = [" + feed + "]");
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    Cursor cursor = adapter.getDownloadLog(Feed.FEEDFILETYPE_FEED, feed.getId());
    List<DownloadStatus> downloadLog = new ArrayList<>(cursor.getCount());
    if (cursor.moveToFirst()) {
        do {
            DownloadStatus status = DownloadStatus.fromCursor(cursor);
            downloadLog.add(status);
        } while (cursor.moveToNext());
    }
    cursor.close();
    adapter.close();
    Collections.sort(downloadLog, new DownloadStatusComparator());
    return downloadLog;
}

74. DBReader#getFeedStatisticsList()

Project: AntennaPod
Source File: DBReader.java
View license
/**
     * Loads the FeedItemStatistics objects of all Feeds in the database. This method should be preferred over
     * {@link #getFeedItemList(Feed)} if only metadata about
     * the FeedItems is needed.
     *
     * @return A list of FeedItemStatistics objects sorted alphabetically by their Feed's title.
     */
public static List<FeedItemStatistics> getFeedStatisticsList() {
    Log.d(TAG, "getFeedStatisticsList() called");
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    List<FeedItemStatistics> result = new ArrayList<>();
    Cursor cursor = adapter.getFeedStatisticsCursor();
    if (cursor.moveToFirst()) {
        do {
            FeedItemStatistics fis = FeedItemStatistics.fromCursor(cursor);
            result.add(fis);
        } while (cursor.moveToNext());
    }
    cursor.close();
    adapter.close();
    return result;
}

75. DBReader#getFeed()

Project: AntennaPod
Source File: DBReader.java
View license
static Feed getFeed(final long feedId, PodDBAdapter adapter) {
    Feed feed = null;
    Cursor feedCursor = adapter.getFeedCursor(feedId);
    if (feedCursor.moveToFirst()) {
        feed = extractFeedFromCursorRow(adapter, feedCursor);
        feed.setItems(getFeedItemList(feed));
    } else {
        Log.e(TAG, "getFeed could not find feed with id " + feedId);
    }
    feedCursor.close();
    return feed;
}

76. DBReader#getFeedItem()

Project: AntennaPod
Source File: DBReader.java
View license
static FeedItem getFeedItem(final String podcastUrl, final String episodeUrl, PodDBAdapter adapter) {
    Log.d(TAG, "Loading feeditem with podcast url " + podcastUrl + " and episode url " + episodeUrl);
    FeedItem item = null;
    Cursor itemCursor = adapter.getFeedItemCursor(podcastUrl, episodeUrl);
    if (itemCursor.moveToFirst()) {
        List<FeedItem> list = extractItemlistFromCursor(adapter, itemCursor);
        if (list.size() > 0) {
            item = list.get(0);
            loadAdditionalFeedItemListData(list);
            if (item.hasChapters()) {
                loadChaptersOfFeedItem(adapter, item);
            }
        }
    }
    itemCursor.close();
    return item;
}

77. DBReader#loadExtraInformationOfFeedItem()

Project: AntennaPod
Source File: DBReader.java
View license
/**
     * Loads additional information about a FeedItem, e.g. shownotes
     *
     * @param item    The FeedItem
     */
public static void loadExtraInformationOfFeedItem(final FeedItem item) {
    Log.d(TAG, "loadExtraInformationOfFeedItem() called with: " + "item = [" + item + "]");
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    Cursor extraCursor = adapter.getExtraInformationOfItem(item);
    if (extraCursor.moveToFirst()) {
        int indexDescription = extraCursor.getColumnIndex(PodDBAdapter.KEY_DESCRIPTION);
        String description = extraCursor.getString(indexDescription);
        int indexContentEncoded = extraCursor.getColumnIndex(PodDBAdapter.KEY_CONTENT_ENCODED);
        String contentEncoded = extraCursor.getString(indexContentEncoded);
        item.setDescription(description);
        item.setContentEncoded(contentEncoded);
    }
    extraCursor.close();
    adapter.close();
}

78. DBTasks#removeFeedWithDownloadUrl()

Project: AntennaPod
Source File: DBTasks.java
View license
/**
     * Removes the feed with the given download url. This method should NOT be executed on the GUI thread.
     *
     * @param context     Used for accessing the db
     * @param downloadUrl URL of the feed.
     */
public static void removeFeedWithDownloadUrl(Context context, String downloadUrl) {
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    Cursor cursor = adapter.getFeedCursorDownloadUrls();
    long feedID = 0;
    if (cursor.moveToFirst()) {
        do {
            if (cursor.getString(1).equals(downloadUrl)) {
                feedID = cursor.getLong(0);
            }
        } while (cursor.moveToNext());
    }
    cursor.close();
    adapter.close();
    if (feedID != 0) {
        try {
            DBWriter.deleteFeed(context, feedID).get();
        } catch (InterruptedExceptionExecutionException |  e) {
            e.printStackTrace();
        }
    } else {
        Log.w(TAG, "removeFeedWithDownloadUrl: Could not find feed with url: " + downloadUrl);
    }
}

79. PodDBAdapter#getFlattrQueueSize()

Project: AntennaPod
Source File: PodDBAdapter.java
View license
/**
     * Counts feeds and feed items in the flattr queue
     */
public int getFlattrQueueSize() {
    int res = 0;
    Cursor c = db.rawQuery(String.format("SELECT count(*) FROM %s WHERE %s=%s", TABLE_NAME_FEEDS, KEY_FLATTR_STATUS, String.valueOf(FlattrStatus.STATUS_QUEUE)), null);
    if (c.moveToFirst()) {
        res = c.getInt(0);
        c.close();
    } else {
        Log.e(TAG, "Unable to determine size of flattr queue: Could not count number of feeds");
    }
    c = db.rawQuery(String.format("SELECT count(*) FROM %s WHERE %s=%s", TABLE_NAME_FEED_ITEMS, KEY_FLATTR_STATUS, String.valueOf(FlattrStatus.STATUS_QUEUE)), null);
    if (c.moveToFirst()) {
        res += c.getInt(0);
        c.close();
    } else {
        Log.e(TAG, "Unable to determine size of flattr queue: Could not count number of feed items");
    }
    return res;
}

80. PodDBAdapter#getNumberOfNewItems()

Project: AntennaPod
Source File: PodDBAdapter.java
View license
public final int getNumberOfNewItems() {
    final String query = "SELECT COUNT(" + KEY_ID + ")" + " FROM " + TABLE_NAME_FEED_ITEMS + " WHERE " + KEY_READ + "=" + FeedItem.NEW;
    Cursor c = db.rawQuery(query, null);
    int result = 0;
    if (c.moveToFirst()) {
        result = c.getInt(0);
    }
    c.close();
    return result;
}

81. PodDBAdapter#getNumberOfDownloadedEpisodes()

Project: AntennaPod
Source File: PodDBAdapter.java
View license
public final int getNumberOfDownloadedEpisodes() {
    final String query = "SELECT COUNT(DISTINCT " + KEY_ID + ") AS count FROM " + TABLE_NAME_FEED_MEDIA + " WHERE " + KEY_DOWNLOADED + " > 0";
    Cursor c = db.rawQuery(query, null);
    int result = 0;
    if (c.moveToFirst()) {
        result = c.getInt(0);
    }
    c.close();
    return result;
}

82. ContactHelper#getMainProfileContactName()

Project: apg
Source File: ContactHelper.java
View license
/**
     * Retrieves the name of the primary profile contact
     * http://developer.android.com/reference/android/provider/ContactsContract.Profile.html
     *
     * @param context
     * @return
     */
public static List<String> getMainProfileContactName(Context context) {
    ContentResolver resolver = context.getContentResolver();
    Cursor profileCursor = resolver.query(ContactsContract.Profile.CONTENT_URI, new String[] { ContactsContract.Profile.DISPLAY_NAME }, null, null, null);
    if (profileCursor == null) {
        return null;
    }
    Set<String> names = new HashSet<>();
    // should only contain one entry!
    while (profileCursor.moveToNext()) {
        String name = profileCursor.getString(0);
        if (name != null) {
            names.add(name);
        }
    }
    profileCursor.close();
    return new ArrayList<>(names);
}

83. ContactHelper#getContactMails()

Project: apg
Source File: ContactHelper.java
View license
public static List<String> getContactMails(Context context) {
    ContentResolver resolver = context.getContentResolver();
    Cursor mailCursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, new String[] { ContactsContract.CommonDataKinds.Email.DATA }, null, null, null);
    if (mailCursor == null) {
        return new ArrayList<>();
    }
    Set<String> mails = new HashSet<>();
    while (mailCursor.moveToNext()) {
        String email = mailCursor.getString(0);
        if (email != null) {
            mails.add(email);
        }
    }
    mailCursor.close();
    return new ArrayList<>(mails);
}

84. ContactHelper#getContactNames()

Project: apg
Source File: ContactHelper.java
View license
public static List<String> getContactNames(Context context) {
    ContentResolver resolver = context.getContentResolver();
    Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null);
    if (cursor == null) {
        return new ArrayList<>();
    }
    Set<String> names = new HashSet<>();
    while (cursor.moveToNext()) {
        String name = cursor.getString(0);
        if (name != null) {
            names.add(name);
        }
    }
    cursor.close();
    return new ArrayList<>(names);
}

85. HistoryEntryDatabaseTable#convertAllTitlesToUnderscores()

View license
/**
     * One-time fix for the inconsistencies in title formats all over the database. This migration will enforce
     * all titles stored in the database to follow the "Underscore_format" instead of the "Human readable form"
     * TODO: Delete this code after April 2016
     *
     * @param db Database object
     */
private void convertAllTitlesToUnderscores(SQLiteDatabase db) {
    Cursor cursor = db.query(getTableName(), null, null, null, null, null, null);
    ContentValues values = new ContentValues();
    while (cursor.moveToNext()) {
        String title = Col.TITLE.val(cursor);
        if (title.contains(" ")) {
            values.put(Col.TITLE.getName(), title.replace(" ", "_"));
            String id = Long.toString(Col.ID.val(cursor));
            db.updateWithOnConflict(getTableName(), values, Col.ID.getName() + " = ?", new String[] { id }, SQLiteDatabase.CONFLICT_REPLACE);
        }
    }
    cursor.close();
}

86. PageImageDatabaseTable#convertAllTitlesToUnderscores()

View license
/**
     * One-time fix for the inconsistencies in title formats all over the database. This migration will enforce
     * all titles stored in the database to follow the "Underscore_format" instead of the "Human readable form"
     * TODO: Delete this code after April 2016
     *
     * @param db Database object
     */
private void convertAllTitlesToUnderscores(SQLiteDatabase db) {
    Cursor cursor = db.query(getTableName(), null, null, null, null, null, null);
    ContentValues values = new ContentValues();
    while (cursor.moveToNext()) {
        String title = Col.TITLE.val(cursor);
        if (title.contains(" ")) {
            values.put(Col.TITLE.getName(), title.replace(" ", "_"));
            String id = Long.toString(Col.ID.val(cursor));
            db.updateWithOnConflict(getTableName(), values, Col.ID.getName() + " = ?", new String[] { id }, SQLiteDatabase.CONFLICT_REPLACE);
        }
    }
    cursor.close();
}

87. SavedPageDatabaseTable#convertAllTitlesToUnderscores()

View license
/**
     * One-time fix for the inconsistencies in title formats all over the database. This migration will enforce
     * all titles stored in the database to follow the "Underscore_format" instead of the "Human readable form"
     * TODO: Delete this code after April 2016
     *
     * @param db Database object
     */
private void convertAllTitlesToUnderscores(SQLiteDatabase db) {
    Cursor cursor = db.query(getTableName(), null, null, null, null, null, null);
    ContentValues values = new ContentValues();
    while (cursor.moveToNext()) {
        String title = Col.TITLE.val(cursor);
        if (title.contains(" ")) {
            values.put(Col.TITLE.getName(), title.replace(" ", "_"));
            String id = Long.toString(Col.ID.val(cursor));
            db.updateWithOnConflict(getTableName(), values, Col.ID.getName() + " = ?", new String[] { id }, SQLiteDatabase.CONFLICT_REPLACE);
            SavedPage obj = fromPreNamespaceCursor(cursor, Col.NAMESPACE.val(cursor), null);
            String savedPageBaseDir = FileUtil.savedPageBaseDir();
            File newDir = new File(savedPageBaseDir + "/" + obj.getTitle().getIdentifier());
            new File(savedPageBaseDir + "/" + getSavedPageDir(obj, title)).renameTo(newDir);
        }
    }
    cursor.close();
}

88. TaskController#fetchTaskCursor()

Project: astrid
Source File: TaskController.java
View license
/** Returns null if unsuccessful, otherwise moves cursor to the task.
     * Don't forget to close the cursor when you're done. */
private Cursor fetchTaskCursor(String name, long creationDate, String[] fieldList) {
    // truncate millis
    final String where = AbstractTaskModel.NAME + " = ? AND " + AbstractTaskModel.CREATION_DATE + " LIKE ?";
    String approximateCreationDate = (creationDate / 1000) + "%";
    Cursor cursor = database.query(true, tasksTable, fieldList, where, new String[] { name, approximateCreationDate }, null, null, null, null);
    if (cursor == null)
        throw new SQLException("Returned empty set!");
    if (cursor.moveToFirst()) {
        return cursor;
    }
    cursor.close();
    return null;
}

89. LegacyTasksXmlExporter#serializeTasks()

Project: astrid
Source File: LegacyTasksXmlExporter.java
View license
private void serializeTasks() throws IOException {
    Cursor c = taskController.getBackupTaskListCursor();
    if (!c.moveToFirst()) {
        // No tasks.
        return;
    }
    do {
        TaskModelForXml task = new TaskModelForXml(c);
        TaskIdentifier taskId = task.getTaskIdentifier();
        xml.startTag(null, TASK_TAG);
        HashMap<String, String> taskAttributes = task.getTaskAttributes();
        for (String key : taskAttributes.keySet()) {
            String value = taskAttributes.get(key);
            xml.attribute(null, key, value);
        }
        serializeTags(taskId);
        serializeAlerts(taskId);
        serializeSyncMappings(taskId);
        xml.endTag(null, TASK_TAG);
        this.exportCount++;
    } while (c.moveToNext());
    c.close();
}

90. Utility#getOrientation()

Project: astrid
Source File: Utility.java
View license
public static int getOrientation(Context context, Uri photoUri) {
    /* it's on the external media. */
    Cursor cursor = context.getContentResolver().query(photoUri, new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
    if (cursor.getCount() != 1) {
        return -1;
    }
    cursor.moveToFirst();
    int orientation = cursor.getInt(0);
    cursor.close();
    return orientation;
}

91. AddressDatabaseHelper#v3ToV4()

View license
private void v3ToV4(SQLiteDatabase db) {
    // v1.3.3 ensure v2 & v3 's script executed.
    Cursor cursor = db.rawQuery("select count(0) from sqlite_master where name='aliases'", null);
    int cnt = 0;
    if (cursor.moveToNext()) {
        cnt = cursor.getInt(0);
    }
    cursor.close();
    if (cnt == 0) {
        v1ToV2(db);
        v2ToV3(db);
    }
}

92. EnterpriseHDMProvider#getPubCount()

View license
@Override
public int getPubCount() {
    SQLiteDatabase db = this.mDb.getReadableDatabase();
    int pubCount = 0;
    Cursor cursor = db.rawQuery("select multi_sign_m from enterprise_multi_sign_set", null);
    if (cursor.moveToNext()) {
        int idColumn = cursor.getColumnIndex(AbstractDb.EnterpriseMultiSignSetColumns.MULTI_SIGN_M);
        if (idColumn != -1) {
            pubCount = cursor.getInt(idColumn);
        }
    }
    cursor.close();
    return pubCount;
}

93. EnterpriseHDMProvider#getThreshold()

View license
@Override
public int getThreshold() {
    SQLiteDatabase db = this.mDb.getReadableDatabase();
    int threshold = 0;
    Cursor cursor = db.rawQuery("select multi_sign_n from enterprise_multi_sign_set", null);
    if (cursor.moveToNext()) {
        int idColumn = cursor.getColumnIndex(AbstractDb.EnterpriseMultiSignSetColumns.MULTI_SIGN_N);
        if (idColumn != -1) {
            threshold = cursor.getInt(idColumn);
        }
    }
    cursor.close();
    return threshold;
}

94. CatalogueDBAdapter#deleteAnthologyTitle()

View license
/**
	 * Delete the anthology record with the given rowId (not to be confused with the book rowId
	 * 
	 * @param anthRowId id of the anthology to delete
	 * @return true if deleted, false otherwise
	 */
public boolean deleteAnthologyTitle(long anthRowId, boolean dirtyBookIfNecessary) {
    // Find the soon to be deleted title position#
    Cursor anthology = fetchAnthologyTitleById(anthRowId);
    anthology.moveToFirst();
    int position = anthology.getInt(anthology.getColumnIndexOrThrow(CatalogueDBAdapter.KEY_POSITION));
    int book = anthology.getInt(anthology.getColumnIndexOrThrow(CatalogueDBAdapter.KEY_BOOK));
    anthology.close();
    boolean success;
    // Delete the title
    success = mDb.delete(DB_TB_ANTHOLOGY, KEY_ROWID + "=" + anthRowId, null) > 0;
    purgeAuthors();
    // Move all titles past the deleted book up one position
    String sql = "UPDATE " + DB_TB_ANTHOLOGY + " SET " + KEY_POSITION + "=" + KEY_POSITION + "-1" + " WHERE " + KEY_POSITION + ">" + position + " AND " + KEY_BOOK + "=" + book + "";
    mDb.execSQL(sql);
    if (dirtyBookIfNecessary)
        setBookDirty(book);
    return success;
}

95. MultitypeListAdapter#getSectionTextForPosition()

View license
@Override
public String[] getSectionTextForPosition(final int position) {
    final Cursor c = getCursor();
    if (position < 0 || position >= c.getCount())
        return null;
    final int savedPos = c.getPosition();
    c.moveToPosition(position);
    final String[] section = mHandler.getSectionText(c);
    c.moveToPosition(savedPos);
    return section;
}

96. DataStore#findCaches()

Project: cgeo
Source File: DataStore.java
View license
private static void findCaches(final SearchSuggestionCursor resultCursor, final String selectionArg) {
    final Cursor cursor = database.query(dbTableCaches, new String[] { "geocode", "name", "type" }, "geocode IS NOT NULL AND geocode != '' AND (geocode LIKE ? OR name LIKE ? OR owner LIKE ?)", new String[] { selectionArg, selectionArg, selectionArg }, null, null, "name");
    while (cursor.moveToNext()) {
        final String geocode = cursor.getString(0);
        final String cacheName = cursor.getString(1);
        final String type = cursor.getString(2);
        resultCursor.addCache(geocode, cacheName, type);
    }
    cursor.close();
}

97. DataStore#findTrackables()

Project: cgeo
Source File: DataStore.java
View license
private static void findTrackables(final MatrixCursor resultCursor, final String selectionArg) {
    final Cursor cursor = database.query(dbTableTrackables, new String[] { "tbcode", "title" }, "tbcode IS NOT NULL AND tbcode != '' AND (tbcode LIKE ? OR title LIKE ?)", new String[] { selectionArg, selectionArg }, null, null, "title");
    while (cursor.moveToNext()) {
        final String tbcode = cursor.getString(0);
        resultCursor.addRow(new String[] { String.valueOf(resultCursor.getCount()), cursor.getString(1), tbcode, Intents.ACTION_TRACKABLE, tbcode, String.valueOf(R.drawable.trackable_all) });
    }
    cursor.close();
}

98. EmoticonDBHelper#getUriByTag()

Project: ChatKeyboard
Source File: EmoticonDBHelper.java
View license
public synchronized String getUriByTag(String tag) {
    SQLiteDatabase db = mOpenDbHelper.getReadableDatabase();
    String sql = "select * from " + TABLE_NAME_EMOTICONS + " where " + TableColumns.EmoticonColumns.TAG + " = '" + tag + "'";
    Cursor cursor = db.rawQuery(sql, null);
    if (cursor.getCount() <= 0) {
        cursor.close();
        return null;
    }
    cursor.moveToFirst();
    //first check msg uri
    String msgUri = cursor.getString(cursor.getColumnIndex(TableColumns.EmoticonColumns.MSG_URI));
    if (msgUri != null) {
        cursor.close();
        return msgUri;
    }
    // if msgUri is null, use icon uri
    String iconUri = cursor.getString(cursor.getColumnIndex(TableColumns.EmoticonColumns.ICON_URI));
    cursor.close();
    return iconUri;
}

99. ContactListManagerAdapter#loadOfflineContacts()

View license
private void loadOfflineContacts() {
    Cursor contactCursor = mResolver.query(mContactUrl, new String[] { Imps.Contacts.USERNAME, Imps.Contacts.NICKNAME }, null, null, null);
    String[] addresses = new String[contactCursor.getCount()];
    int i = 0;
    while (contactCursor.moveToNext()) {
        addresses[i++] = contactCursor.getString(0);
    }
    Contact[] contacts = mAdaptee.createTemporaryContacts(addresses);
    for (Contact contact : contacts) mOfflineContacts.put(contact.getAddress().getBareAddress(), contact);
    contactCursor.close();
}

100. ContactListManagerAdapter#isSubscribed()

View license
boolean isSubscribed(String username) {
    boolean result = false;
    Cursor cursor = mResolver.query(mContactUrl, new String[] { Imps.Contacts._ID }, Imps.Contacts.USERNAME + "=? AND " + Imps.Contacts.SUBSCRIPTION_STATUS + "=" + Imps.Contacts.SUBSCRIPTION_STATUS_NONE, new String[] { username }, null);
    if (cursor == null) {
        RemoteImService.debug("query contact " + username + " failed");
        return false;
    }
    if (cursor.moveToFirst()) {
        result = true;
    }
    cursor.close();
    return result;
}