Exemple #1
0
  private static synchronized 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;
  }
Exemple #2
0
  private FinalDb(DaoConfig config) {
    if (config == null) throw new DbException("daoConfig is null");
    if (config.getContext() == null) throw new DbException("android context is null");
    if (config.type == 1) {
      File file = new File(config.getContext().getFilesDir(), config.getDbName());
      if (!file.exists()) {
        // 拷贝数据库
        try {
          InputStream is = config.getContext().getAssets().open(config.getDbName());
          Utils.copyFile(is, file);

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      this.db = SQLiteDatabase.openOrCreateDatabase(file, null);
    } else if (config.getTargetDirectory() != null
        && config.getTargetDirectory().trim().length() > 0
        && config.type != 1) {
      this.db = createDbFileOnSDCard(config.getTargetDirectory(), config.getDbName());
    } else {
      this.db =
          new SqliteDbHelper(
                  config.getContext().getApplicationContext(),
                  config.getDbName(),
                  config.getDbVersion(),
                  config.getDbUpdateListener())
              .getWritableDatabase();
    }
    this.config = config;
  }