下面列出了android.database.sqlite.SQLiteDatabase#getPath ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public long getSize()
{
long size = 0;
synchronized(databaseLock) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
File databaseFile = new File(database.getPath());
if(databaseFile.exists()) {
size = databaseFile.length();
} else {
Log.w(SERVICENAME, "DB not null, File does not exist!");
}
}
return size;
}
@Test
public void verifyDeleteAfterCorruptionWhileOpen() {
Context context = ApplicationProvider.getApplicationContext();
JobStorage jobStorage = new JobStorage(context);
SQLiteDatabase database = jobStorage.getDatabase();
assertThat(database).isNotNull();
assertThat(database.isOpen()).isTrue();
File file = new File(database.getPath());
assertThat(file.exists()).isTrue();
assertThat(file.isFile()).isTrue();
new JobStorageDatabaseErrorHandler().onCorruption(database);
assertThat(file.exists()).isFalse();
}
@Test
public void verifyDeleteAfterCorruptionWhileClosed() {
Context context = ApplicationProvider.getApplicationContext();
JobStorage jobStorage = new JobStorage(context);
SQLiteDatabase database = jobStorage.getDatabase();
assertThat(database).isNotNull();
assertThat(database.isOpen()).isTrue();
File file = new File(database.getPath());
assertThat(file.exists()).isTrue();
assertThat(file.isFile()).isTrue();
database.close();
new JobStorageDatabaseErrorHandler().onCorruption(database);
assertThat(file.exists()).isFalse();
}
@Test
public void verifyDeleteWithApi14() {
Context context = ApplicationProvider.getApplicationContext();
JobStorage jobStorage = new JobStorage(context);
SQLiteDatabase database = jobStorage.getDatabase();
assertThat(database).isNotNull();
assertThat(database.isOpen()).isTrue();
File file = new File(database.getPath());
assertThat(file.exists()).isTrue();
assertThat(file.isFile()).isTrue();
new JobStorageDatabaseErrorHandler().deleteApi14(context, file);
assertThat(file.exists()).isFalse();
}
@Test
public void verifyDeleteWhileOpening() {
Context context = ApplicationProvider.getApplicationContext();
String filePath = getClass().getResource("/databases/corrupted.db").getPath();
final long originalLength = new File(filePath).length();
assertThat(new File(filePath).exists()).isTrue();
JobStorage jobStorage = new JobStorage(context, filePath);
SQLiteDatabase database = jobStorage.getDatabase();
assertThat(database).isNotNull();
assertThat(database.isOpen()).isTrue();
assertThat(originalLength).isNotEqualTo(new File(filePath).length());
File databaseFile = new File(database.getPath());
assertThat(databaseFile.exists()).isTrue();
assertThat(databaseFile.isFile()).isTrue();
}
public boolean removeOfflineMapDatabase(OfflineMapDatabase offlineMapDatabase) {
// Mark the offline map object as invalid in case there are any references to it still floating around
//
offlineMapDatabase.invalidate();
// Remove the offline map object from the array and delete it's backing database
//
mutableOfflineMapDatabases.remove(offlineMapDatabase);
// Remove Offline Database SQLite file
SQLiteDatabase db = OfflineDatabaseManager.getOfflineDatabaseManager(context).getOfflineDatabaseHandlerForMapId(offlineMapDatabase.getMapID()).getReadableDatabase();
String dbPath = db.getPath();
db.close();
File dbFile = new File(dbPath);
boolean result = dbFile.delete();
Log.i(TAG, String.format(MAPBOX_LOCALE, "Result of removing database file: %s", result));
return result;
}
/**
* constructor would create or open the database
* @param context if you wouldn't call updateTable, you can pass null to contxt;
* @param dbName
*/
public DbSqlite(Context context, SQLiteDatabase db){
this.mContext = context;
this.mSQLiteDatabase = db;
this.dbPath = db.getPath();
openDB();
}
public void deleteDatabase() {
// Are you sure? (y/n)
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final File dbFile = new File(db.getPath());
mOpenHelper.close();
if (dbFile.exists()) {
SQLiteDatabase.deleteDatabase(dbFile);
}
mOpenHelper = new DatabaseHelper(getContext());
mOpenHelper.mListener = mListener;
}
public String getPath()
{
String path;
synchronized(databaseLock) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
path = database.getPath();
}
return path;
}
public void deleteDatabase() {
// Are you sure? (y/n)
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final File dbFile = new File(db.getPath());
mOpenHelper.close();
if (dbFile.exists()) {
SQLiteDatabase.deleteDatabase(dbFile);
}
mOpenHelper = new DatabaseHelper(getContext());
}
/**
* Validate the header of the database file to verify it is a sqlite database
*
* @param sqliteDatabase database
*/
private void validateDatabaseHeader(SQLiteDatabase sqliteDatabase) {
boolean validHeader = isDatabaseHeaderValid(sqliteDatabase);
if (!validHeader) {
throw new GeoPackageException(
"GeoPackage SQLite header is not valid: " + sqliteDatabase.getPath());
}
}
/**
* Validate the integrity of the database
*
* @param sqliteDatabase database
*/
private void validateDatabaseIntegrity(SQLiteDatabase sqliteDatabase) {
if (!sqliteDatabase.isDatabaseIntegrityOk()) {
throw new GeoPackageException(
"GeoPackage SQLite file integrity failed: " + sqliteDatabase.getPath());
}
}
public void deleteDatabase() {
// Are you sure? (y/n)
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final File dbFile = new File(db.getPath());
mOpenHelper.close();
if (dbFile.exists()) {
SQLiteDatabase.deleteDatabase(dbFile);
}
mOpenHelper = new DatabaseHelper(getContext());
}
public boolean initializeDatabase() {
String uniqueID = sqliteMetadataForName("uniqueID");
String mapID = sqliteMetadataForName("mapID");
String includesMetadata = sqliteMetadataForName("includesMetadata");
String includesMarkers = sqliteMetadataForName("includesMarkers");
String imageQuality = sqliteMetadataForName("imageQuality");
if (TextUtils.isEmpty(uniqueID)) {
uniqueID = String.format(MAPBOX_LOCALE, "%s-%d", mapID, new Date().getTime() / 1000L);
}
if (!TextUtils.isEmpty(mapID) && !TextUtils.isEmpty(includesMetadata) && !TextUtils.isEmpty(includesMarkers) && !TextUtils.isEmpty(imageQuality)) {
// Reaching this point means that the specified database file at path pointed to an sqlite file which had
// all the required values in its metadata table. That means the file passed the test for being a valid
// offline map database.
//
this.uniqueID = uniqueID;
this.mapID = mapID;
this.includesMetadata = "YES".equalsIgnoreCase(includesMetadata);
this.includesMarkers = "YES".equalsIgnoreCase(includesMarkers);
this.imageQuality = RasterImageQuality.getEnumForValue(Integer.parseInt(imageQuality));
SQLiteDatabase db = database();
this.path = db.getPath();
this.initializedProperly = true;
} else {
// Reaching this point means the file at path isn't a valid offline map database, so we can't use it.
Log.w(TAG, "Invalid offline map database. Can't be used.");
}
return initializedProperly;
}
public DbSqlite(Context context, SQLiteDatabase db){
this.mContext = context;
this.mSQLiteDatabase = db;
this.dbPath = db.getPath();
openDB();
}
private void establishDbTracking(int userHandle) {
if (LOCAL_LOGV) {
Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
}
DatabaseHelper dbhelper;
synchronized (this) {
dbhelper = mOpenHelpers.get(userHandle);
if (dbhelper == null) {
dbhelper = new DatabaseHelper(getContext(), userHandle);
mOpenHelpers.append(userHandle, dbhelper);
sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
}
}
// Initialization of the db *outside* the locks. It's possible that racing
// threads might wind up here, the second having read the cache entries
// written by the first, but that's benign: the SQLite helper implementation
// manages concurrency itself, and it's important that we not run the db
// initialization with any of our own locks held, so we're fine.
SQLiteDatabase db = dbhelper.getWritableDatabase();
// Watch for external modifications to the database files,
// keeping our caches in sync. We synchronize the observer set
// separately, and of course it has to run after the db file
// itself was set up by the DatabaseHelper.
synchronized (sObserverInstances) {
if (sObserverInstances.get(userHandle) == null) {
SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
sObserverInstances.append(userHandle, observer);
observer.startWatching();
}
}
ensureAndroidIdIsSet(userHandle);
startAsyncCachePopulation(userHandle);
}
@Provides
File provideHackerNewsDatabaseFile(SQLiteDatabase sqLiteDatabase) {
return new File(sqLiteDatabase.getPath());
}
public DatabaseBackupHelper(Context ctx, SQLiteDatabase database) {
super(ctx, database.getPath());
}
public OfflineMapDatabase completeDatabaseAndInstantiateOfflineMapWithError() {
/*
if (AppUtils.runningOnMainThread()) {
Log.w(TAG, "completeDatabaseAndInstantiateOfflineMapWithError() running on main thread. Returning null.");
return null;
}
*/
// Rename database file (remove -PARTIAL) and update path in db object, update path in OfflineMapDatabase, create new Handler
SQLiteDatabase db = database();
String dbPath = db.getPath();
closeDatabase();
if (dbPath.endsWith("-PARTIAL")) {
// Rename SQLlite database file
File oldDb = new File(dbPath);
String newDb = dbPath.substring(0, dbPath.indexOf("-PARTIAL"));
boolean result = oldDb.renameTo(new File(newDb));
Log.i(TAG, "Result of rename = " + result + " for oldDb = '" + dbPath + "'; newDB = '" + newDb + "'");
}
// Update Database Handler
OfflineDatabaseManager.getOfflineDatabaseManager(context).switchHandlerFromPartialToRegular(mapID);
// Create DB object and return
OfflineMapDatabase offlineMapDatabase = new OfflineMapDatabase(context, mapID);
// Initialized with data from database
offlineMapDatabase.initializeDatabase();
return offlineMapDatabase;
// Create new OfflineMapDatabase and load with recently downloaded data
/*
// Rename the file using a unique prefix
//
CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, uuid);
NSString *newFilename = [NSString stringWithFormat:@"%@.complete",uuidString];
NSString *newPath = [[_offlineMapDirectory URLByAppendingPathComponent:newFilename] path];
CFRelease(uuidString);
CFRelease(uuid);
[[NSFileManager defaultManager] moveItemAtPath:_partialDatabasePath toPath:newPath error:error];
// If the move worked, instantiate and return offline map database
//
if(error && *error)
{
return nil;
}
else
{
return [[MBXOfflineMapDatabase alloc] initWithContentsOfFile:newPath];
}
*/
}
/**
* Initialize a new tile layer, represented by a Database file.
*
* @param db a database used as the MBTiles source
*/
public MBTilesLayer(final SQLiteDatabase db) {
super(getFileName(db.getPath()), db.getPath());
initialize(db);
}