Java Code Examples for android.database.DatabaseUtils#queryNumEntries()

The following examples show how to use android.database.DatabaseUtils#queryNumEntries() . 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: BookmarksSQLite.java    From Beedio with GNU General Public License v2.0 6 votes vote down vote up
private void delete(String table, int position) {
    if (getType(table, position).equals("folder")) {
        deleteFolderContents(table + "_" + position);
    }

    for (int i = position + 1; i <= DatabaseUtils.queryNumEntries(bookmarksDB, table); i++) {
        Cursor c = bookmarksDB.query(table, new String[]{"type"}, "oid = " + i, null,
                null, null, null);
        if (c.moveToNext() && c.getString(c.getColumnIndex("type")).equals("folder")) {
            String tablename = table + "_" + i;
            String newTablename = table + "_" + (i - 1);
            bookmarksDB.execSQL("ALTER TABLE " + tablename + " RENAME TO " + newTablename);
            renameSubFolderTables(tablename, newTablename);
            if (tablename.equals(currentTable)) {
                currentTable = newTablename;
            }
        }
        c.close();
        onBookmarkPositionChangedListener.onBookmarkPositionChanged(i, i - 1);
    }

    bookmarksDB.execSQL("DELETE FROM " + table + " WHERE oid = " + position);
    bookmarksDB.execSQL("VACUUM");
    onBookmarkPositionChangedListener.onBookmarkPositionChanged(position, -1);
}
 
Example 2
Source File: MainActivity.java    From Open-Source-Android-Weather-App with MIT License 6 votes vote down vote up
private void checkDatabaseState() {
    if (DatabaseHelper.isTableExists(database, TABLE_1)) {
        long count = DatabaseUtils.queryNumEntries(database, TABLE_1);
        System.out.println(count);
        Log.d(TAG, "checkDatabaseState: start checking database");
        if (count != 168820) {
            database.execSQL("DROP TABLE IF EXISTS " + TABLE_1);
            databaseHelper.createTable1(database);
            createLocalCityDB();
            Log.d(TAG, "checkDatabaseState: database is broken");
        }
    } else {
        databaseHelper.createTable1(database);
        createLocalCityDB();
        Log.d(TAG, "checkDatabaseState: first start database");
    }
}
 
Example 3
Source File: LeanplumEventDataManager.java    From Leanplum-Android-SDK with Apache License 2.0 5 votes vote down vote up
/**
 * Gets number of rows in the event table.
 *
 * @return Number of rows in the event table.
 */
long getEventsCount() {
  long count = 0;
  if (database == null) {
    return count;
  }
  try {
    count = DatabaseUtils.queryNumEntries(database, EVENT_TABLE_NAME);
    sendErrorLogs = false;
  } catch (Throwable t) {
    handleSQLiteError("Unable to get a number of rows in the table.", t);
  }
  return count;
}
 
Example 4
Source File: LocationTable.java    From openlocate-android with MIT License 5 votes vote down vote up
static long size(SQLiteDatabase database) {
    if (database == null) {
        return 0;
    }

    return DatabaseUtils.queryNumEntries(database, TABLE_NAME);
}
 
Example 5
Source File: VersionTable.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@VisibleForTesting
/* package */ static boolean tableExists(SQLiteDatabase readableDatabase, String tableName) {
  long count =
      DatabaseUtils.queryNumEntries(
          readableDatabase, "sqlite_master", "tbl_name = ?", new String[] {tableName});
  return count > 0;
}
 
Example 6
Source File: SQLiteLocationDAO.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
public long getLocationsForSyncCount(long millisSinceLastBatch) {
  String whereClause = TextUtils.join("", new String[]{
          SQLiteLocationContract.LocationEntry.COLUMN_NAME_STATUS + " = ? AND ( ",
          SQLiteLocationContract.LocationEntry.COLUMN_NAME_BATCH_START_MILLIS + " IS NULL OR ",
          SQLiteLocationContract.LocationEntry.COLUMN_NAME_BATCH_START_MILLIS + " < ? )",
  });
  String[] whereArgs = {
          String.valueOf(BackgroundLocation.SYNC_PENDING),
          String.valueOf(millisSinceLastBatch)
  };

  return DatabaseUtils.queryNumEntries(db, LocationEntry.TABLE_NAME, whereClause, whereArgs);
}
 
Example 7
Source File: VersionTable.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
@VisibleForTesting
/* package */ static boolean tableExists(SQLiteDatabase readableDatabase, String tableName) {
  long count =
      DatabaseUtils.queryNumEntries(
          readableDatabase, "sqlite_master", "tbl_name = ?", new String[] {tableName});
  return count > 0;
}
 
Example 8
Source File: CbDb.java    From PressureNet-SDK with MIT License 4 votes vote down vote up
/**
 * Get last week pressure count
 * @return
 */
public long getLast7dPressureCount() {
	return DatabaseUtils.queryNumEntries(mDB,  OBSERVATIONS_TABLE,
               KEY_TIME + " > ?", new String[] {System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 7) + ""});
}
 
Example 9
Source File: ContactDBHelper.java    From Android-Debug-Database with Apache License 2.0 4 votes vote down vote up
public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
    return numRows;
}
 
Example 10
Source File: ComprehensionDb.java    From BuildmLearn-Toolkit-Android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public long getCountQuestions() {

        return DatabaseUtils.queryNumEntries(db,
                Questions.TABLE_NAME);
    }
 
Example 11
Source File: GroupDb.java    From XERUNG with Apache License 2.0 4 votes vote down vote up
public long countTest() {
    SQLiteDatabase sq = this.getWritableDatabase();
    return DatabaseUtils.queryNumEntries(sq, TABLE_NAME);
}
 
Example 12
Source File: QuizDb.java    From BuildmLearn-Toolkit-Android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public long getCountQuestions() {

        return DatabaseUtils.queryNumEntries(db,
                Questions.TABLE_NAME);
    }
 
Example 13
Source File: Index.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
public boolean processDownloadedHillshade(int x, int y, String filePath, @Nullable ProgressListener progressListener) {
    File mapFile = new File(filePath);
    try {
        logger.error("Importing from {}", mapFile.getName());
        SQLiteDatabase database = SQLiteDatabase.openDatabase(filePath, null, SQLiteDatabase.OPEN_READONLY);

        int total = 0, progress = 0;
        if (progressListener != null) {
            total += DatabaseUtils.queryNumEntries(database, TABLE_TILES);
            progressListener.onProgressStarted(total);
        }

        // copy tiles
        SQLiteStatement statement = mHillshadeDatabase.compileStatement("REPLACE INTO " + TABLE_TILES + " VALUES (?,?,?,?)");
        mHillshadeDatabase.beginTransaction();
        Cursor cursor = database.query(TABLE_TILES, ALL_COLUMNS_TILES, null, null, null, null, null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            statement.clearBindings();
            statement.bindLong(1, cursor.getInt(0));
            statement.bindLong(2, cursor.getInt(1));
            statement.bindLong(3, cursor.getInt(2));
            statement.bindBlob(4, cursor.getBlob(3));
            statement.execute();
            if (progressListener != null) {
                progress++;
                progressListener.onProgressChanged(progress);
            }
            cursor.moveToNext();
        }
        cursor.close();
        mHillshadeDatabase.setTransactionSuccessful();
        mHillshadeDatabase.endTransaction();
        logger.error("  imported tiles");

        byte version = 0;
        cursor = database.query(TABLE_INFO, new String[]{COLUMN_INFO_VALUE}, WHERE_INFO_NAME, new String[]{"version"}, null, null, null);
        if (cursor.moveToFirst())
            version = (byte) Integer.valueOf(cursor.getString(0)).intValue();
        cursor.close();
        database.close();
        if (!mHasHillshades) {
            Configuration.setHillshadesEnabled(true);
            mHasHillshades = true;
        }
        setHillshadeDownloaded(x, y, version);
    } catch (SQLiteException e) {
        MapTrek.getApplication().registerException(e);
        logger.error("Import failed", e);
        return false;
    } finally {
        if (mHillshadeDatabase.inTransaction())
            mHillshadeDatabase.endTransaction();
        if (progressListener != null)
            progressListener.onProgressFinished();
        //noinspection ResultOfMethodCallIgnored
        mapFile.delete();
    }
    return true;
}
 
Example 14
Source File: SettingsActivity.java    From your-local-weather with GNU General Public License v3.0 4 votes vote down vote up
private String getDataFromCacheDB() {

            ReverseGeocodingCacheDbHelper mDbHelper = ReverseGeocodingCacheDbHelper.getInstance(getActivity());
            SQLiteDatabase db = mDbHelper.getReadableDatabase();
            long numberOfRowsInAddress = DatabaseUtils.queryNumEntries(db, ReverseGeocodingCacheContract.LocationAddressCache.TABLE_NAME);

            StringBuilder lastRowsFromDB = new StringBuilder();

            lastRowsFromDB.append("There are ");
            lastRowsFromDB.append(numberOfRowsInAddress);
            lastRowsFromDB.append(" of rows in cache.\n\n");

            String[] projection = {
                    ReverseGeocodingCacheContract.LocationAddressCache.COLUMN_NAME_ADDRESS,
                    ReverseGeocodingCacheContract.LocationAddressCache.COLUMN_NAME_CREATED,
                    ReverseGeocodingCacheContract.LocationAddressCache._ID
            };

            String sortOrder = ReverseGeocodingCacheContract.LocationAddressCache.COLUMN_NAME_CREATED + " DESC";

            Cursor cursor = db.query(
                    ReverseGeocodingCacheContract.LocationAddressCache.TABLE_NAME,
                    projection,
                    null,
                    null,
                    null,
                    null,
                    sortOrder
            );

            int rowsCounter = 0;

            while(cursor.moveToNext()) {

                if (!cursor.isFirst()) {
                    lastRowsFromDB.append("\n");
                }

                byte[] cachedAddressBytes = cursor.getBlob(
                        cursor.getColumnIndexOrThrow(ReverseGeocodingCacheContract.LocationAddressCache.COLUMN_NAME_ADDRESS));
                Address address = ReverseGeocodingCacheDbHelper.getAddressFromBytes(cachedAddressBytes);

                long recordCreatedinMilis = cursor.getLong(cursor.getColumnIndexOrThrow(ReverseGeocodingCacheContract.LocationAddressCache.COLUMN_NAME_CREATED));
                String recordCreatedTxt = iso8601Format.format(new Date(recordCreatedinMilis));

                int itemId = cursor.getInt(cursor.getColumnIndexOrThrow(ReverseGeocodingCacheContract.LocationAddressCache._ID));

                lastRowsFromDB.append(itemId);
                lastRowsFromDB.append(" : ");
                lastRowsFromDB.append(recordCreatedTxt);
                lastRowsFromDB.append(" : ");
                if (address.getLocality() != null) {
                    lastRowsFromDB.append(address.getLocality());
                    if (!address.getLocality().equals(address.getSubLocality())) {
                        lastRowsFromDB.append(" - ");
                        lastRowsFromDB.append(address.getSubLocality());
                    }
                }

                rowsCounter++;
                if (rowsCounter > 7) {
                    break;
                }
            }
            cursor.close();

            return lastRowsFromDB.toString();
        }
 
Example 15
Source File: BaseDatabaseHelper.java    From mobile-messaging-sdk-android with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends DatabaseContract.DatabaseObject> long countAll(Class<T> cls, String sqlWhereCondition) {
    return DatabaseUtils.queryNumEntries(db(), getTableName(cls), sqlWhereCondition);
}
 
Example 16
Source File: Index.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
public Index(Context context, SQLiteDatabase mapsDatabase, SQLiteDatabase hillshadesDatabase) {
    mContext = context;
    mMapsDatabase = mapsDatabase;
    mHillshadeDatabase = hillshadesDatabase;
    mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

    try {
        Cursor cursor = mMapsDatabase.query(TABLE_MAPS, ALL_COLUMNS_MAPS, WHERE_MAPS_PRESENT, null, null, null, null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            int x = cursor.getInt(cursor.getColumnIndex(COLUMN_MAPS_X));
            int y = cursor.getInt(cursor.getColumnIndex(COLUMN_MAPS_Y));
            short date = cursor.getShort(cursor.getColumnIndex(COLUMN_MAPS_DATE));
            byte version = (byte) cursor.getShort(cursor.getColumnIndex(COLUMN_MAPS_VERSION));
            logger.debug("index({}, {}, {}, {})", x, y, date, version);
            if (x == -1 && y == -1) {
                mBaseMapVersion = date;
                cursor.moveToNext();
                continue;
            }
            long downloading = cursor.getLong(cursor.getColumnIndex(COLUMN_MAPS_DOWNLOADING));
            long hillshadeDownloading = cursor.getLong(cursor.getColumnIndex(COLUMN_MAPS_HILLSHADE_DOWNLOADING));
            MapStatus mapStatus = getNativeMap(x, y);
            mapStatus.created = date;
            mapStatus.hillshadeVersion = version;
            int status = checkDownloadStatus(downloading);
            if (status == DownloadManager.STATUS_PAUSED
                    || status == DownloadManager.STATUS_PENDING
                    || status == DownloadManager.STATUS_RUNNING) {
                mapStatus.downloading = downloading;
                logger.debug("  map downloading: {}", downloading);
            } else {
                downloading = 0L;
                setDownloading(x, y, downloading, hillshadeDownloading);
                logger.debug("  cleared");
            }
            status = checkDownloadStatus(hillshadeDownloading);
            if (status == DownloadManager.STATUS_PAUSED
                    || status == DownloadManager.STATUS_PENDING
                    || status == DownloadManager.STATUS_RUNNING) {
                mapStatus.hillshadeDownloading = hillshadeDownloading;
                logger.debug("  hillshade downloading: {}", downloading);
            } else {
                hillshadeDownloading = 0L;
                setDownloading(x, y, downloading, hillshadeDownloading);
                logger.debug("  cleared");
            }
            if (date > 0)
                mLoadedMaps++;
            cursor.moveToNext();
        }
        cursor.close();
    } catch (SQLiteException e) {
        logger.error("Failed to read map index", e);
        mMapsDatabase.execSQL(MapTrekDatabaseHelper.SQL_CREATE_MAPS);
        mMapsDatabase.execSQL(MapTrekDatabaseHelper.SQL_INDEX_MAPS);
    }
    mHasHillshades = DatabaseUtils.queryNumEntries(mHillshadeDatabase, TABLE_TILES) > 0;

    //TODO Remove old basemap file
}
 
Example 17
Source File: ExampleDBHelper.java    From android-sqlite-sample with MIT License 4 votes vote down vote up
public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, PERSON_TABLE_NAME);
    return numRows;
}
 
Example 18
Source File: HistoryDatabase.java    From JumpGo with Mozilla Public License 2.0 4 votes vote down vote up
@WorkerThread
synchronized long getHistoryItemsCount() {
    return DatabaseUtils.queryNumEntries(mDatabase, TABLE_HISTORY);
}
 
Example 19
Source File: GeometryMetadataDataSource.java    From geopackage-android with MIT License 2 votes vote down vote up
/**
 * Query for all table geometry metadata count matching the envelope
 *
 * @param geoPackageId GeoPackage id
 * @param tableName    table name
 * @param envelope     geometry envelope
 * @return count
 * @since 3.4.0
 */
public long count(long geoPackageId, String tableName, GeometryEnvelope envelope) {
    return DatabaseUtils.queryNumEntries(db.getAndroidSQLiteDatabase().getDb(), GeometryMetadata.TABLE_NAME, querySQL(envelope), querySQLArgs(envelope, geoPackageId, tableName));
}
 
Example 20
Source File: EventStore.java    From snowplow-android-tracker with Apache License 2.0 2 votes vote down vote up
/**
 * Returns amount of events currently
 * in the database.
 *
 * @return the count of events in the
 * database
 */
public long getSize() {
    return DatabaseUtils.queryNumEntries(database, EventStoreHelper.TABLE_EVENTS);
}