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

The following examples show how to use android.database.sqlite.SQLiteDatabase#getVersion() . 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: DatabaseHelper.java    From AndroidDemo with MIT License 6 votes vote down vote up
public static Response getAllTableName(SQLiteDatabase database) {
    Response response = new Response();
    Cursor c = database.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
    if (c.moveToFirst()) {
        while (!c.isAfterLast()) {
            response.rows.add(c.getString(0));
            c.moveToNext();
        }
    }
    c.close();
    response.isSuccessful = true;
    try {
        response.dbVersion = database.getVersion();
    } catch (Exception ignore) {

    }
    return response;
}
 
Example 2
Source File: DatabaseHelper.java    From AndroidDemo with MIT License 6 votes vote down vote up
public static Response getAllTableName(SQLiteDatabase database) {
    Response response = new Response();
    Cursor c = database.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
    if (c.moveToFirst()) {
        while (!c.isAfterLast()) {
            response.rows.add(c.getString(0));
            c.moveToNext();
        }
    }
    c.close();
    response.isSuccessful = true;
    try {
        response.dbVersion = database.getVersion();
    } catch (Exception ignore) {

    }
    return response;
}
 
Example 3
Source File: MeasurementsDatabase.java    From TowerCollector with Mozilla Public License 2.0 6 votes vote down vote up
public static int getDatabaseVersion(Context context) {
    int version = DATABASE_FILE_VERSION;
    SQLiteDatabase db = null;
    try {
        File path = context.getDatabasePath(DATABASE_FILE_NAME);
        // open manually to prevent database upgrade or creation
        db = SQLiteDatabase.openDatabase(path.toString(), null, SQLiteDatabase.OPEN_READONLY);
        version = db.getVersion(); // equivalent of PRAGMA user_version
        Timber.d("getDatabaseVersion(): Database file version %s", version);
    } catch (SQLiteException ex) {
        Timber.e(ex, "getDatabaseVersion(): Database file cannot be opened");
    } finally {
        if (db != null)
            db.close();
    }
    return version;
}
 
Example 4
Source File: SqliteHelper.java    From vault with Apache License 2.0 6 votes vote down vote up
private boolean isPendingCopy(File dbPath) {
  boolean result = false;
  if (dbPath.exists()) {
    SQLiteDatabase db =
        context.openOrCreateDatabase(spaceHelper.getDatabaseName(), Context.MODE_PRIVATE, null);
    try {
      if (spaceHelper.getDatabaseVersion() > db.getVersion()) {
        result = true;
      }
    } finally {
      db.close();
    }
  } else {
    result = true;
  }
  return result;
}
 
Example 5
Source File: MediaDatabase.java    From VCL-Android with Apache License 2.0 5 votes vote down vote up
@Override
public SQLiteDatabase getWritableDatabase() {
    SQLiteDatabase db;
    try {
        return super.getWritableDatabase();
    } catch(SQLiteException e) {
        try {
            db = SQLiteDatabase.openOrCreateDatabase(VLCApplication.getAppContext().getDatabasePath(DB_NAME), null);
        } catch(SQLiteException e2) {
            Log.w(TAG, "SQLite database could not be created! Media library cannot be saved.");
            db = SQLiteDatabase.create(null);
        }
    }
    int version = db.getVersion();
    if (version != DB_VERSION) {
        db.beginTransaction();
        try {
            if (version == 0) {
                onCreate(db);
            } else {
                onUpgrade(db, version, DB_VERSION);
            }
            db.setVersion(DB_VERSION);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }
    return db;
}
 
Example 6
Source File: SQLiteOpenHelper.java    From YiBo with Apache License 2.0 5 votes vote down vote up
/**
 * Create and/or open a database.  This will be the same object returned by
 * {@link #getWritableDatabase} unless some problem, such as a full disk,
 * requires the database to be opened read-only.  In that case, a read-only
 * database object will be returned.  If the problem is fixed, a future call
 * to {@link #getWritableDatabase} may succeed, in which case the read-only
 * database object will be closed and the read/write object will be returned
 * in the future.
 *
 * @throws SQLiteException if the database cannot be opened
 * @return a database object valid until {@link #getWritableDatabase}
 *     or {@link #close} is called.
 */
public synchronized SQLiteDatabase getReadableDatabase() {
    if (mDatabase != null && mDatabase.isOpen()) {
        return mDatabase;  // The database is already open for business
    }

    if (mIsInitializing) {
        throw new IllegalStateException("getReadableDatabase called recursively");
    }

    try {
        return getWritableDatabase();
    } catch (SQLiteException e) {
        if (mName == null) throw e;  // Can't open a temp database read-only!
        Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
    }

    SQLiteDatabase db = null;
    try {
        mIsInitializing = true;
        String path = databaseDirectory(mContext) + File.separator + mName;
        db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        if (db.getVersion() != mNewVersion) {
            throw new SQLiteException("Can't upgrade read-only database from version " +
                    db.getVersion() + " to " + mNewVersion + ": " + path);
        }

        onOpen(db);
        Log.w(TAG, "Opened " + mName + " in read-only mode");
        mDatabase = db;
        return mDatabase;
    } finally {
        mIsInitializing = false;
        if (db != null && db != mDatabase) db.close();
    }
}
 
Example 7
Source File: DbUtils.java    From android-open-project-demo with Apache License 2.0 5 votes vote down vote up
private synchronized static DbUtils getInstance(DaoConfig daoConfig) {
    DbUtils dao = daoMap.get(daoConfig.getDbName());
    if (dao == null) {
        dao = new DbUtils(daoConfig);
        daoMap.put(daoConfig.getDbName(), dao);
    } else {
        dao.daoConfig = daoConfig;
    }

    // update the database if needed
    SQLiteDatabase database = dao.database;
    int oldVersion = database.getVersion();
    int newVersion = daoConfig.getDbVersion();
    if (oldVersion != newVersion) { //数据库升级
        if (oldVersion != 0) {
            DbUpgradeListener upgradeListener = daoConfig.getDbUpgradeListener();
            if (upgradeListener != null) {
                upgradeListener.onUpgrade(dao, oldVersion, newVersion);
            } else {
                try {
                    dao.dropDb();
                } catch (DbException e) {
                    LogUtils.e(e.getMessage(), e);
                }
            }
        }
        database.setVersion(newVersion);
    }

    return dao;
}
 
Example 8
Source File: SQLiteAssetHelper.java    From MonsterHunter4UDatabase with MIT License 5 votes vote down vote up
/**
 * Create and/or open a database.  This will be the same object returned by
 * {@link #getWritableDatabase} unless some problem, such as a full disk,
 * requires the database to be opened read-only.  In that case, a read-only
 * database object will be returned.  If the problem is fixed, a future call
 * to {@link #getWritableDatabase} may succeed, in which case the read-only
 * database object will be closed and the read/write object will be returned
 * in the future.
 *
 * <p class="caution">Like {@link #getWritableDatabase}, this method may
 * take a long time to return, so you should not call it from the
 * application main thread, including from
 * {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
 *
 * @throws SQLiteException if the database cannot be opened
 * @return a database object valid until {@link #getWritableDatabase}
 *     or {@link #close} is called.
 */
@Override
public synchronized SQLiteDatabase getReadableDatabase() {
    if (mDatabase != null && mDatabase.isOpen()) {
        return mDatabase;  // The database is already open for business
    }

    if (mIsInitializing) {
        throw new IllegalStateException("getReadableDatabase called recursively");
    }

    try {
        return getWritableDatabase();
    } catch (SQLiteException e) {
        if (mName == null) throw e;  // Can't open a temp database read-only!
        Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
    }

    SQLiteDatabase db = null;
    try {
        mIsInitializing = true;
        String path = mContext.getDatabasePath(mName).getPath();
        db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
        if (db.getVersion() != mNewVersion) {
            throw new SQLiteException("Can't upgrade read-only database from version " +
                    db.getVersion() + " to " + mNewVersion + ": " + path);
        }

        onOpen(db);
        Log.w(TAG, "Opened " + mName + " in read-only mode");
        mDatabase = db;
        return mDatabase;
    } finally {
        mIsInitializing = false;
        if (db != null && db != mDatabase) db.close();
    }
}
 
Example 9
Source File: SQLiteDatabaseHelper.java    From NexusData with Apache License 2.0 5 votes vote down vote up
/**
 * Create and/or open a database.  This will be the same object returned by
 * {@link #getWritableDatabase} unless some problem, such as a full disk,
 * requires the database to be opened read-only.  In that case, a read-only
 * database object will be returned.  If the problem is fixed, a future call
 * to {@link #getWritableDatabase} may succeed, in which case the read-only
 * database object will be closed and the read/write object will be returned
 * in the future.
 *
 * <p class="caution">Like {@link #getWritableDatabase}, this method may
 * take a long time to return, so you should not call it from the
 * application main thread, including from
 * {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
 *
 * @throws SQLiteException if the database cannot be opened
 * @return a database object valid until {@link #getWritableDatabase}
 *     or {@link #close} is called.
 */
public synchronized SQLiteDatabase getReadableDatabase() {
    if (mDatabase != null && mDatabase.isOpen()) {
        return mDatabase;  // The database is already open for business
    }

    if (mIsInitializing) {
        throw new IllegalStateException("getReadableDatabase called recursively");
    }

    try {
        return getWritableDatabase();
    } catch (SQLiteException e) {
        if (mPath.getName() == null) throw e;  // Can't open a temp database read-only!
        LOG.warn("Couldn't open " + mPath.getName() + " for writing (will try read-only):", e);
    }

    SQLiteDatabase db = null;
    try {
        mIsInitializing = true;
        db = SQLiteDatabase.openDatabase(mPath.toString(), mFactory, SQLiteDatabase.OPEN_READONLY);
        if (db.getVersion() != mNewVersion) {
            throw new SQLiteException("Can't upgrade read-only database from version " +
                    db.getVersion() + " to " + mNewVersion + ": " + mPath);
        }

        onOpen(db);
        LOG.warn("Opened " + mPath.getName() + " in read-only mode");
        mDatabase = db;
        return mDatabase;
    } finally {
        mIsInitializing = false;
        if (db != null && db != mDatabase) db.close();
    }
}
 
Example 10
Source File: StatDatabaseHelper.java    From Cangol-appcore with Apache License 2.0 5 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.d("onUpgrade " + oldVersion + "->" + newVersion);
    if (db.getVersion() < DATABASE_VERSION) {
        //do nothings
    }
}
 
Example 11
Source File: DbTools.java    From volley with Apache License 2.0 5 votes vote down vote up
private synchronized static DbTools getInstance(DaoConfig daoConfig) {
    DbTools dao = daoMap.get(daoConfig.getDbName());
    if (dao == null) {
        dao = new DbTools(daoConfig);
        daoMap.put(daoConfig.getDbName(), dao);
    } else {
        dao.daoConfig = daoConfig;
    }

    // update the database if needed
    SQLiteDatabase database = dao.database;
    int oldVersion = database.getVersion();
    int newVersion = daoConfig.getDbVersion();
    if (oldVersion != newVersion) {
        if (oldVersion != 0) {
            DbUpgradeListener upgradeListener = daoConfig.getDbUpgradeListener();
            if (upgradeListener != null) {
                upgradeListener.onUpgrade(dao, oldVersion, newVersion);
            } else {
                try {
                    dao.dropDb();
                } catch (DbException e) {
                    VolleyLog.e(e.getMessage(), e);
                }
            }
        }
        database.setVersion(newVersion);
    }

    return dao;
}
 
Example 12
Source File: AppContext.java    From SqliteLookup with Apache License 2.0 5 votes vote down vote up
private void initDb(){
	SQLiteDatabase db = openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);
	int dbVersion = db.getVersion();
	if(dbVersion == 0){
		db.setVersion(DB_VERSION);
		onCreateTables(db);
	}else if(dbVersion < DB_VERSION){
		db.setVersion(DB_VERSION);
		onUpdateTables(db);
	}
}
 
Example 13
Source File: DbUtils.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
private synchronized static DbUtils getInstance(DaoConfig daoConfig) {
    DbUtils dao = daoMap.get(daoConfig.getDbName());
    if (dao == null) {
        dao = new DbUtils(daoConfig);
        daoMap.put(daoConfig.getDbName(), dao);
    } else {
        dao.daoConfig = daoConfig;
    }

    // update the database if needed
    SQLiteDatabase database = dao.database;
    int oldVersion = database.getVersion();
    int newVersion = daoConfig.getDbVersion();
    if (oldVersion != newVersion) {
        if (oldVersion != 0) {
            DbUpgradeListener upgradeListener = daoConfig.getDbUpgradeListener();
            if (upgradeListener != null) {
                upgradeListener.onUpgrade(dao, oldVersion, newVersion);
            } else {
                try {
                    dao.dropDb();
                } catch (DbException e) {
                    LogUtils.e(e.getMessage(), e);
                }
            }
        }
        database.setVersion(newVersion);
    }

    return dao;
}
 
Example 14
Source File: OrmLiteHelper.java    From AndroidQuick with MIT License 5 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
                      int oldVersion, int newVersion) {
    int old = db.getVersion();
    LogUtil.i("OrmLiteHelper", "[老用户升级]老数据库版本号:" + old);
    update(db, old);
}
 
Example 15
Source File: EhDB.java    From MHViewer with Apache License 2.0 4 votes vote down vote up
/**
 * @param file The db file
 * @return error string, null for no error
 */
public static synchronized String importDB(Context context, File file) {
    try {
        SQLiteDatabase db = SQLiteDatabase.openDatabase(
                file.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        int newVersion = DaoMaster.SCHEMA_VERSION;
        int oldVersion = db.getVersion();
        if (oldVersion < newVersion) {
            upgradeDB(db, oldVersion);
            db.setVersion(newVersion);
        } else if (oldVersion > newVersion) {
            return context.getString(R.string.cant_read_the_file);
        }

        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession session = daoMaster.newSession();

        // Downloads
        DownloadManager manager = EhApplication.getDownloadManager(context);
        List<DownloadInfo> downloadInfoList = session.getDownloadsDao().queryBuilder().list();
        manager.addDownload(downloadInfoList);

        // Download label
        List<DownloadLabel> downloadLabelList = session.getDownloadLabelDao().queryBuilder().list();
        manager.addDownloadLabel(downloadLabelList);

        // Download dirname
        List<DownloadDirname> downloadDirnameList = session.getDownloadDirnameDao().queryBuilder().list();
        for (DownloadDirname dirname : downloadDirnameList) {
            putDownloadDirname(dirname.getGid(), dirname.getDirname());
        }

        // History
        List<HistoryInfo> historyInfoList = session.getHistoryDao().queryBuilder().list();
        putHistoryInfo(historyInfoList);

        // QuickSearch
        List<QuickSearch> quickSearchList = session.getQuickSearchDao().queryBuilder().list();
        List<QuickSearch> currentQuickSearchList = sDaoSession.getQuickSearchDao().queryBuilder().list();
        for (QuickSearch quickSearch : quickSearchList) {
            String name = quickSearch.name;
            for (QuickSearch q : currentQuickSearchList) {
                if (ObjectUtils.equal(q.name, name)) {
                    // The same name
                    name = null;
                    break;
                }
            }
            if (null == name) {
                continue;
            }
            insertQuickSearch(quickSearch);
        }

        // LocalFavorites
        List<LocalFavoriteInfo> localFavoriteInfoList = session.getLocalFavoritesDao().queryBuilder().list();
        for (LocalFavoriteInfo info : localFavoriteInfoList) {
            putLocalFavorites(info);
        }

        // Bookmarks
        // TODO

        List<ReadingRecord> readingRecordList = session.getReadingRecordDao().queryBuilder().list();
        for (ReadingRecord record : readingRecordList) {
            putReadingRecord(record);
        }

        // Filter
        List<Filter> filterList = session.getFilterDao().queryBuilder().list();
        List<Filter> currentFilterList = sDaoSession.getFilterDao().queryBuilder().list();
        for (Filter filter : filterList) {
            if (!currentFilterList.contains(filter)) {
                addFilter(filter);
            }
        }

        return null;
    } catch (Throwable e) {
        ExceptionUtils.throwIfFatal(e);
        // Ignore
        return context.getString(R.string.cant_read_the_file);
    }
}
 
Example 16
Source File: ImportDatabaseActivity.java    From xDrip-Experimental with GNU General Public License v3.0 4 votes vote down vote up
protected String doInBackground(Void... args) {
    //Check if db has the correct version:
    try {
        SQLiteDatabase db = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);
        int version = db.getVersion();
        db.close();
        if (getDBVersion() != version) {
            statusDialog.dismiss();
            return "Wrong Database version.\n(" + version + " instead of " + getDBVersion() + ")";
        }
    } catch (SQLiteException e){
        statusDialog.dismiss();
        return "Database cannot be opened... aborting.";
    }
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            statusDialog.setMessage("Step 2: exporting current DB");
        }
    });

    String export = DatabaseUtil.saveSql(getBaseContext());


    if (export == null) {
        statusDialog.dismiss();
        return "Exporting database not successfull... aborting.";
    }

    mHandler.post(new Runnable() {
        @Override
        public void run() {
            statusDialog.setMessage("Step 3: importing DB");
        }
    });

    String result = DatabaseUtil.loadSql(getBaseContext(), dbFile.getAbsolutePath());

    statusDialog.dismiss();
    return result;
}
 
Example 17
Source File: EhDB.java    From EhViewer with Apache License 2.0 4 votes vote down vote up
/**
 * @param file The db file
 * @return error string, null for no error
 */
public static synchronized String importDB(Context context, File file) {
    try {
        SQLiteDatabase db = SQLiteDatabase.openDatabase(
                file.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        int newVersion = DaoMaster.SCHEMA_VERSION;
        int oldVersion = db.getVersion();
        if (oldVersion < newVersion) {
            upgradeDB(db, oldVersion);
            db.setVersion(newVersion);
        } else if (oldVersion > newVersion) {
            return context.getString(R.string.cant_read_the_file);
        }

        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession session = daoMaster.newSession();

        // Downloads
        DownloadManager manager = EhApplication.getDownloadManager(context);
        List<DownloadInfo> downloadInfoList = session.getDownloadsDao().queryBuilder().list();
        manager.addDownload(downloadInfoList);

        // Download label
        List<DownloadLabel> downloadLabelList = session.getDownloadLabelDao().queryBuilder().list();
        manager.addDownloadLabel(downloadLabelList);

        // Download dirname
        List<DownloadDirname> downloadDirnameList = session.getDownloadDirnameDao().queryBuilder().list();
        for (DownloadDirname dirname: downloadDirnameList) {
            putDownloadDirname(dirname.getGid(), dirname.getDirname());
        }

        // History
        List<HistoryInfo> historyInfoList = session.getHistoryDao().queryBuilder().list();
        putHistoryInfo(historyInfoList);

        // QuickSearch
        List<QuickSearch> quickSearchList = session.getQuickSearchDao().queryBuilder().list();
        List<QuickSearch> currentQuickSearchList = sDaoSession.getQuickSearchDao().queryBuilder().list();
        for (QuickSearch quickSearch: quickSearchList) {
            String name = quickSearch.name;
            for (QuickSearch q: currentQuickSearchList) {
                if (ObjectUtils.equal(q.name, name)) {
                    // The same name
                    name = null;
                    break;
                }
            }
            if (null == name) {
                continue;
            }
            insertQuickSearch(quickSearch);
        }

        // LocalFavorites
        List<LocalFavoriteInfo> localFavoriteInfoList = session.getLocalFavoritesDao().queryBuilder().list();
        for (LocalFavoriteInfo info: localFavoriteInfoList) {
            putLocalFavorites(info);
        }

        // Bookmarks
        // TODO

        // Filter
        List<Filter> filterList = session.getFilterDao().queryBuilder().list();
        List<Filter> currentFilterList = sDaoSession.getFilterDao().queryBuilder().list();
        for (Filter filter: filterList) {
            if (!currentFilterList.contains(filter)) {
                addFilter(filter);
            }
        }

        return null;
    } catch (Throwable e) {
        ExceptionUtils.throwIfFatal(e);
        // Ignore
        return context.getString(R.string.cant_read_the_file);
    }
}
 
Example 18
Source File: SQLiteAssetHelper.java    From MonsterHunter4UDatabase with MIT License 4 votes vote down vote up
/**
 * Create and/or open a database that will be used for reading and writing.
 * The first time this is called, the database will be extracted and copied
 * from the application's assets folder.
 *
 * <p>Once opened successfully, the database is cached, so you can
 * call this method every time you need to write to the database.
 * (Make sure to call {@link #close} when you no longer need the database.)
 * Errors such as bad permissions or a full disk may cause this method
 * to fail, but future attempts may succeed if the problem is fixed.</p>
 *
 * <p class="caution">Database upgrade may take a long time, you
 * should not call this method from the application main thread, including
 * from {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
 *
 * @throws SQLiteException if the database cannot be opened for writing
 * @return a read/write database object valid until {@link #close} is called
 */
@Override
public synchronized SQLiteDatabase getWritableDatabase() {
    if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
        return mDatabase;  // The database is already open for business
    }

    if (mIsInitializing) {
        throw new IllegalStateException("getWritableDatabase called recursively");
    }

    // If we have a read-only database open, someone could be using it
    // (though they shouldn't), which would cause a lock to be held on
    // the file, and our attempts to open the database read-write would
    // fail waiting for the file lock.  To prevent that, we acquire the
    // lock on the read-only database, which shuts out other users.

    boolean success = false;
    SQLiteDatabase db = null;
    //if (mDatabase != null) mDatabase.lock();
    try {
        mIsInitializing = true;
        //if (mName == null) {
        //    db = SQLiteDatabase.create(null);
        //} else {
        //    db = mContext.openOrCreateDatabase(mName, 0, mFactory);
        //}
        db = createOrOpenDatabase(false);

        int version = db.getVersion();

        // do force upgrade
        if (version != 0 && version < mForcedUpgradeVersion) {
            db = createOrOpenDatabase(true);
            db.setVersion(mNewVersion);
            version = db.getVersion();
        }

        if (version != mNewVersion) {
            db.beginTransaction();
            try {
                if (version == 0) {
                    onCreate(db);
                } else {
                    if (version > mNewVersion) {
                        Log.w(TAG, "Can't downgrade read-only database from version " +
                                version + " to " + mNewVersion + ": " + db.getPath());
                    }
                    onUpgrade(db, version, mNewVersion);
                }
                db.setVersion(mNewVersion);
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        }

        onOpen(db);
        success = true;
        return db;
    } finally {
        mIsInitializing = false;
        if (success) {
            if (mDatabase != null) {
                try { mDatabase.close(); } catch (Exception e) { }
                //mDatabase.unlock();
            }
            mDatabase = db;
        } else {
            //if (mDatabase != null) mDatabase.unlock();
            if (db != null) db.close();
        }
    }

}
 
Example 19
Source File: SQLiteSDCardHelper.java    From android-sdcard-helper with Apache License 2.0 4 votes vote down vote up
private SQLiteDatabase getDatabaseLocked(boolean writable){
    if (mDatabase != null) {
        if (!mDatabase.isOpen()) {
            // Darn!  The user closed the database by calling mDatabase.close().
            mDatabase = null;
        } else if (!writable || !mDatabase.isReadOnly()) {
            // The database is already open for business.
            return mDatabase;
        }
    }

    if (mIsInitializing) {
        throw new IllegalStateException("getDatabase called recursively");
    }
    // If we have a read-only database open, someone could be using it
    // (though they shouldn't), which would cause a lock to be held on
    // the file, and our attempts to open the database read-write would
    // fail waiting for the file lock.  To prevent that, we acquire the
    // lock on the read-only database, which shuts out other users.

    SQLiteDatabase db = mDatabase;
    try {
        mIsInitializing = true;

        if (db != null) {
            //close  read-only databases, create a new writable
            if (writable && db.isReadOnly()) {
                db.close();
            }
        }

        try {
            db = openDatabase(SQLiteDatabase.OPEN_READWRITE);
        } catch (SQLiteException e) {
            // Couldn't open the DB, let's try to create it.
            Log.e(TAG, "Couldn't open " + mName
                    + " for writing (will try read-only):", e);
            // Here if we fail, we propagate the exception to our user.
            db = openDatabase(SQLiteDatabase.OPEN_READONLY);
        }

        onConfigure(db);

        final int version = db.getVersion();
        if (version != mNewVersion) {
            if (db.isReadOnly()) {
                throw new SQLiteException("Can't upgrade read-only database from version " +
                        db.getVersion() + " to " + mNewVersion + ": " + mName);
            }

            db.beginTransaction();
            try {
                if (version == 0) {
                    onCreate(db);
                } else {
                    if (version > mNewVersion) {
                        onDowngrade(db, version, mNewVersion);
                    } else {
                        onUpgrade(db, version, mNewVersion);
                    }
                }
                db.setVersion(mNewVersion);
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        }

        onOpen(db);

        if (db.isReadOnly()) {
            Log.w(TAG, "Opened " + mName + " in read-only mode");
        }

        mDatabase = db;
        return db;
    }finally {
        mIsInitializing = false;
        if (db != null && db != mDatabase) {
            db.close();
        }
    }
}
 
Example 20
Source File: SQLiteOpenHelper.java    From YiBo with Apache License 2.0 4 votes vote down vote up
/**
 * Create and/or open a database that will be used for reading and writing.
 * Once opened successfully, the database is cached, so you can call this
 * method every time you need to write to the database.  Make sure to call
 * {@link #close} when you no longer need it.
 *
 * <p>Errors such as bad permissions or a full disk may cause this operation
 * to fail, but future attempts may succeed if the problem is fixed.</p>
 *
 * @throws SQLiteException if the database cannot be opened for writing
 * @return a read/write database object valid until {@link #close} is called
 */
public synchronized SQLiteDatabase getWritableDatabase() {
    if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
        return mDatabase;  // The database is already open for business
    }

    if (mIsInitializing) {
        throw new IllegalStateException("getWritableDatabase called recursively");
    }

    // If we have a read-only database open, someone could be using it
    // (though they shouldn't), which would cause a lock to be held on
    // the file, and our attempts to open the database read-write would
    // fail waiting for the file lock.  To prevent that, we acquire the
    // lock on the read-only database, which shuts out other users.

    boolean success = false;
    SQLiteDatabase db = null;
    try {
        mIsInitializing = true;
        if (mName == null) {
            db = SQLiteDatabase.create(null);
        } else {
        	String path = databaseDirectory(mContext) + File.separator + mName;
        	db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        }

        int version = db.getVersion();
        if (version != mNewVersion) {
            db.beginTransaction();
            try {
                if (version == 0) {
                    onCreate(db);
                } else {
                    onUpgrade(db, version, mNewVersion);
                }
                db.setVersion(mNewVersion);
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        }

        onOpen(db);
        success = true;
        return db;
    } finally {
        mIsInitializing = false;
        if (success) {
            if (mDatabase != null) {
                try { mDatabase.close(); } catch (Exception e) { }
            }
            mDatabase = db;
        } else {
            if (db != null) db.close();
        }
    }
}