Java Code Examples for android.database.sqlite.SQLiteDatabase#getPath()

The following examples show how to use android.database.sqlite.SQLiteDatabase#getPath() . 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: OfflineMapDownloader.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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;
}
 
Example 2
Source File: DatabaseCorruptionTest.java    From android-job with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 3
Source File: DatabaseCorruptionTest.java    From android-job with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 4
Source File: SQLDBController.java    From sensordatacollector with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: DatabaseCorruptionTest.java    From android-job with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 6
Source File: DatabaseCorruptionTest.java    From android-job with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 7
Source File: OfflineMapDatabase.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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;
    }
 
Example 8
Source File: LauncherProvider.java    From LB-Launcher with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 9
Source File: GeoPackageManagerImpl.java    From geopackage-android with MIT License 5 votes vote down vote up
/**
 * 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());
    }
}
 
Example 10
Source File: GeoPackageManagerImpl.java    From geopackage-android with MIT License 5 votes vote down vote up
/**
 * 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());
    }
}
 
Example 11
Source File: LauncherProvider.java    From TurboLauncher with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 12
Source File: SQLDBController.java    From sensordatacollector with GNU General Public License v2.0 5 votes vote down vote up
public String getPath()
{
    String path;

    synchronized(databaseLock) {
        SQLiteDatabase database = databaseHelper.getWritableDatabase();
        path = database.getPath();
    }

    return path;
}
 
Example 13
Source File: LauncherProvider.java    From Trebuchet with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: DbSqlite.java    From SqliteLookup with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 15
Source File: TestsModule.java    From PhilHackerNews with MIT License 4 votes vote down vote up
@Provides
File provideHackerNewsDatabaseFile(SQLiteDatabase sqLiteDatabase) {
    return new File(sqLiteDatabase.getPath());
}
 
Example 16
Source File: DatabaseBackupHelper.java    From android-device-identification with Apache License 2.0 4 votes vote down vote up
public DatabaseBackupHelper(Context ctx, SQLiteDatabase database) {
    super(ctx, database.getPath());
}
 
Example 17
Source File: OfflineMapDownloader.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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];
        }
*/
    }
 
Example 18
Source File: SettingsProvider.java    From Study_Android_Demo with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 19
Source File: DbSqlite.java    From Collection-Android with MIT License 4 votes vote down vote up
public DbSqlite(Context context, SQLiteDatabase db){
	this.mContext = context;
	this.mSQLiteDatabase = db;
	this.dbPath = db.getPath();
	openDB();
}
 
Example 20
Source File: MBTilesLayer.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * 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);
}