下面列出了android.database.DatabaseUtils#queryNumEntries ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
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");
}
}
@VisibleForTesting
/* package */ static boolean tableExists(SQLiteDatabase readableDatabase, String tableName) {
long count =
DatabaseUtils.queryNumEntries(
readableDatabase, "sqlite_master", "tbl_name = ?", new String[] {tableName});
return count > 0;
}
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);
}
@VisibleForTesting
/* package */ static boolean tableExists(SQLiteDatabase readableDatabase, String tableName) {
long count =
DatabaseUtils.queryNumEntries(
readableDatabase, "sqlite_master", "tbl_name = ?", new String[] {tableName});
return count > 0;
}
static long size(SQLiteDatabase database) {
if (database == null) {
return 0;
}
return DatabaseUtils.queryNumEntries(database, TABLE_NAME);
}
/**
* 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;
}
@WorkerThread
synchronized long getHistoryItemsCount() {
return DatabaseUtils.queryNumEntries(mDatabase, TABLE_HISTORY);
}
/**
* 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) + ""});
}
public int numberOfRows() {
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, PERSON_TABLE_NAME);
return numRows;
}
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
}
@Override
public <T extends DatabaseContract.DatabaseObject> long countAll(Class<T> cls, String sqlWhereCondition) {
return DatabaseUtils.queryNumEntries(db(), getTableName(cls), sqlWhereCondition);
}
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();
}
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;
}
public long getCountQuestions() {
return DatabaseUtils.queryNumEntries(db,
Questions.TABLE_NAME);
}
public long countTest() {
SQLiteDatabase sq = this.getWritableDatabase();
return DatabaseUtils.queryNumEntries(sq, TABLE_NAME);
}
public long getCountQuestions() {
return DatabaseUtils.queryNumEntries(db,
Questions.TABLE_NAME);
}
public int numberOfRows() {
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}
/**
* 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));
}
/**
* 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);
}