Example #1
0
  /**
   * Opens the database, and upgrades it if necessary.
   *
   * @param context the Context to use for opening the database
   * @param databaseFile Name of the file to be initialized.
   */
  private void initDatabase(Context context, String databaseFile) {
    try {
      mDatabase = context.openOrCreateDatabase(databaseFile, 0, null);
    } catch (SQLiteException e) {
      // try again by deleting the old db and create a new one
      if (context.deleteDatabase(databaseFile)) {
        mDatabase = context.openOrCreateDatabase(databaseFile, 0, null);
      }
    }

    if (mDatabase == null) {
      // Not much we can do to recover at this point
      Log.e(LOGTAG, "Unable to open or create " + databaseFile);
      return;
    }

    if (mDatabase.getVersion() != DATABASE_VERSION) {
      mDatabase.beginTransactionNonExclusive();
      try {
        createTable();
        mDatabase.setTransactionSuccessful();
      } finally {
        mDatabase.endTransaction();
      }
    }
  }
  private void initDatabase(Context context) {
    try {
      mDatabase = context.openOrCreateDatabase(DATABASE_FILE, 0, null);
    } catch (SQLiteException e) {
      // try again by deleting the old db and create a new one
      if (context.deleteDatabase(DATABASE_FILE)) {
        mDatabase = context.openOrCreateDatabase(DATABASE_FILE, 0, null);
      }
    }
    mDatabase.enableWriteAheadLogging();

    // mDatabase should not be null,
    // the only case is RequestAPI test has problem to create db
    if (mDatabase == null) {
      mInitialized = true;
      notify();
      return;
    }

    if (mDatabase.getVersion() != DATABASE_VERSION) {
      mDatabase.beginTransactionNonExclusive();
      try {
        upgradeDatabase();
        mDatabase.setTransactionSuccessful();
      } finally {
        mDatabase.endTransaction();
      }
    }

    // use per table Mutex lock, turn off database lock, this
    // improves performance as database's ReentrantLock is
    // expansive
    mDatabase.setLockingEnabled(false);
  }
  private void initCacheDatabase(Context context) {
    assert !JniUtil.useChromiumHttpStack();

    try {
      mCacheDatabase = context.openOrCreateDatabase(CACHE_DATABASE_FILE, 0, null);
    } catch (SQLiteException e) {
      // try again by deleting the old db and create a new one
      if (context.deleteDatabase(CACHE_DATABASE_FILE)) {
        mCacheDatabase = context.openOrCreateDatabase(CACHE_DATABASE_FILE, 0, null);
      }
    }
    mCacheDatabase.enableWriteAheadLogging();

    // mCacheDatabase should not be null,
    // the only case is RequestAPI test has problem to create db
    if (mCacheDatabase == null) {
      mInitialized = true;
      notify();
      return;
    }

    if (mCacheDatabase.getVersion() != CACHE_DATABASE_VERSION) {
      mCacheDatabase.beginTransactionNonExclusive();
      try {
        upgradeCacheDatabase();
        bootstrapCacheDatabase();
        mCacheDatabase.setTransactionSuccessful();
      } finally {
        mCacheDatabase.endTransaction();
      }
      // Erase the files from the file system in the
      // case that the database was updated and the
      // there were existing cache content
      CacheManager.removeAllCacheFiles();
    }

    // use read_uncommitted to speed up READ
    mCacheDatabase.execSQL("PRAGMA read_uncommitted = true;");
    // as only READ can be called in the
    // non-WebViewWorkerThread, and read_uncommitted is used,
    // we can turn off database lock to use transaction.
    mCacheDatabase.setLockingEnabled(false);

    // use InsertHelper for faster insertion
    mCacheInserter = new DatabaseUtils.InsertHelper(mCacheDatabase, "cache");
    mCacheUrlColIndex = mCacheInserter.getColumnIndex(CACHE_URL_COL);
    mCacheFilePathColIndex = mCacheInserter.getColumnIndex(CACHE_FILE_PATH_COL);
    mCacheLastModifyColIndex = mCacheInserter.getColumnIndex(CACHE_LAST_MODIFY_COL);
    mCacheETagColIndex = mCacheInserter.getColumnIndex(CACHE_ETAG_COL);
    mCacheExpiresColIndex = mCacheInserter.getColumnIndex(CACHE_EXPIRES_COL);
    mCacheExpiresStringColIndex = mCacheInserter.getColumnIndex(CACHE_EXPIRES_STRING_COL);
    mCacheMimeTypeColIndex = mCacheInserter.getColumnIndex(CACHE_MIMETYPE_COL);
    mCacheEncodingColIndex = mCacheInserter.getColumnIndex(CACHE_ENCODING_COL);
    mCacheHttpStatusColIndex = mCacheInserter.getColumnIndex(CACHE_HTTP_STATUS_COL);
    mCacheLocationColIndex = mCacheInserter.getColumnIndex(CACHE_LOCATION_COL);
    mCacheContentLengthColIndex = mCacheInserter.getColumnIndex(CACHE_CONTENTLENGTH_COL);
    mCacheContentDispositionColIndex = mCacheInserter.getColumnIndex(CACHE_CONTENTDISPOSITION_COL);
    mCacheCrossDomainColIndex = mCacheInserter.getColumnIndex(CACHE_CROSSDOMAIN_COL);
  }
  public ArrayList<sms> getSms() {
    SQLiteDatabase db =
        context.openOrCreateDatabase(
            "urgency_contact.db", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE, null);
    db.execSQL(
        "create table if not exists contact("
            + "_id integer primary key autoincrement,"
            + "phone text not null,"
            + "body text not null"
            + ")");
    Cursor c = db.query("contact", null, null, null, null, null, null);

    if (c != null) {
      ArrayList<sms> smsList = new ArrayList<BlockListData.sms>();
      while (c.moveToNext()) {
        sms s = new sms();
        // String phone=c.getString(c.getColumnIndex("phone"));
        // s.setPhone(phone);
        String body = c.getString(c.getColumnIndex("body"));
        s.setBody(body);
        smsList.add(s);
      }
      c.close();
      db.close();
      return smsList;

    } else {
      ArrayList<sms> smsl = new ArrayList<BlockListData.sms>();
      return smsl;
    }
  }
  public ArrayList<String> getNewsPaperNames() {
    Cursor result;
    ArrayList<String> newsPaperNames = new ArrayList<String>();

    try {
      db = appCtx.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);
      result =
          db.query(
              true, tableName, new String[] {"NewsPaperName"}, null, null, null, null, null, null);

      result.moveToFirst();

      int newsPaperNameIndex = result.getColumnIndex("NewsPaperName");
      while (!result.isAfterLast()) {
        newsPaperNames.add(result.getString(newsPaperNameIndex));
        result.moveToNext();
      }

      result.close();
      db.close();
    } catch (SQLiteException exception) {
      Log.e("NewsPaperTableHandler::getNewsPaperNames", "Failed to get newspaper names");
    } catch (Exception exception) {
      Log.e("NewsPaperTableHandler::getNewsPaperNames", exception.getMessage());
    }

    return newsPaperNames;
  }
 public void displayUsers() {
   SQLiteDatabase db;
   db = mContext.openOrCreateDatabase("SpecApplicationDB", Context.MODE_PRIVATE, null);
   System.out.println(
       "///////////////////The Database table 'user' content/////////////////////////");
   Cursor c = db.rawQuery("SELECT * FROM user", null);
   while (c.moveToNext()) {
     System.out.println(
         "id="
             + c.getInt(0)
             + "-"
             + "login="******"-"
             + "password="******"-"
             + "name="
             + c.getString(3)
             + "-"
             + "occupation="
             + c.getString(4));
   }
   c.close();
 }
Example #7
0
  @Override
  public List<Lecture> getLectures(String query) {

    String sql = null;
    Cursor cur = null;
    SQLiteDatabase newlecDB =
        context.openOrCreateDatabase("newlecture", Context.MODE_PRIVATE, null);

    if (query.equals("") || query == null) {
      sql = "SELECT * FROM Lectures";
      cur = newlecDB.rawQuery(sql, null);
    } else {
      sql = "SELECT * FROM Lectures WHERE Title like ?";
      cur = newlecDB.rawQuery(sql, new String[] {"%" + query + "%"});
    }

    List<Lecture> list = new ArrayList<Lecture>();
    while (cur.moveToNext()) {
      Lecture lecture = new Lecture();
      lecture.setCode(cur.getString(0));
      lecture.setTitle(cur.getString(1));
      lecture.setDegree(cur.getString(2));
      lecture.setPrice(cur.getInt(3));
      lecture.setImage(BitmapFactory.decodeResource(context.getResources(), R.drawable.sam));

      list.add(lecture);
    }

    cur.close();
    newlecDB.close();

    return list;
  }
Example #8
0
 /**
  * 构造
  *
  * @param context
  */
 public BookDao(Context context) {
   // 打开/创建数据库
   db = context.openOrCreateDatabase(MyApp.DBNAME, Context.MODE_PRIVATE, null);
   if (ExistTable(db, SchemeCreator.BTNAME) == false) {
     // 创建表
     db.execSQL(SchemeCreator.getGetBTableSQL());
   }
 }
 public UserDBAdapter open() throws SQLException {
   mDb = mCtx.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
   try {
     mDb.query(DATABASE_TABLE, new String[] {KEY_ID}, null, null, null, null, null);
   } catch (Exception e) {
     mDb.execSQL(DATABASE_CREATE);
   }
   return this;
 }
Example #10
0
  public NLLectureDao(Context context) {
    this.context = context;

    SQLiteDatabase newlecDB =
        context.openOrCreateDatabase("newlecture", Context.MODE_PRIVATE, null);
    newlecDB.execSQL(
        "CREATE TABLE IF NOT EXISTS Lectures("
            + "Code Text, Title Text, Degree Text, Price integer, Image Text)");
  }
  // DEBUG ONLY :: Remove in release
  public void deleteTable() {

    try {
      db = appCtx.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);
      db.delete(tableName, null, null);
      db.close();
    } catch (SQLiteException exception) {
      Log.e("deleteTable", exception.getMessage());
    }
  }
Example #12
0
  public DbAdapter open() throws SQLException {

    try {
      mDB = mCtx.openOrCreateDatabase(DB_NAME, DB_VERSION, null);
      mDB.execSQL(DB_CREATE);
    } catch (SQLException e1) {
      Log.d("DB", "Database exist");
    }
    return this;
  }
Example #13
0
  // Constructor
  public arXivDB(Context ctx) {

    try {
      db = ctx.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
      db.execSQL(CREATE_TABLE_HISTORY);
      db.execSQL(CREATE_TABLE_FEEDS);
      db.execSQL(CREATE_TABLE_FONTSIZE);
    } catch (Exception e) {
    }
  }
Example #14
0
 /** Open the meta-db */
 private static void openDB(Context context) {
   try {
     mMetaDb = context.openOrCreateDatabase(DATABASE_NAME, 0, null);
     if (mMetaDb.needUpgrade(DATABASE_VERSION)) {
       mMetaDb = upgradeDB(mMetaDb, DATABASE_VERSION);
     }
     Timber.v("Opening MetaDB");
   } catch (Exception e) {
     Timber.e(e, "Error opening MetaDB ");
   }
 }
  // For now I'll have this create the DB as well
  public void createTable() {

    try {
      db = appCtx.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);
      db.execSQL(CREATE_TABLE_FEEDS);
      Log.d("Path for the DB", db.getPath());
      db.close();
    } catch (SQLiteException exception) {
      Log.e("NewsPaperTableHandler::createTable", "Could not create the DB or the tables.");
    }
  }
 public boolean updateQuery(ContentValues values, String whereClause, String[] whereArgs) {
   int numRows = 0;
   try {
     db = appCtx.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);
     numRows = db.update(tableName, values, whereClause, whereArgs);
     db.close();
   } catch (SQLiteException exception) {
     Log.e(
         "NewsPaperTableHandler::updateQuery", "Update checkbox failed" + exception.getMessage());
   }
   return numRows == 1 ? true : false;
 }
  public ArrayList<ArrayList<Feed>> getCategoriesForNewsPapers(ArrayList<String> newsPaperNames) {
    Cursor result = null;
    ArrayList<ArrayList<Feed>> categories = new ArrayList<ArrayList<Feed>>();
    ArrayList<Feed> category = new ArrayList<Feed>();

    try {
      db = appCtx.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);

      for (String newsPaper : newsPaperNames) {
        result =
            db.query(
                tableName,
                new String[] {"Category", "FeedURL", "Subscribed"},
                "NewsPaperName=?",
                new String[] {newsPaper},
                null,
                null,
                null);
        result.moveToFirst();
        Feed feed = new Feed();

        int categoryIndex = result.getColumnIndex("Category");
        int subscribedIndex = result.getColumnIndex("Subscribed");
        int feedUrlIndex = result.getColumnIndex("FeedURL");
        // Add to corresponding array list
        while (!result.isAfterLast()) {
          feed.setNewsPaper(newsPaper);
          feed.setCategory(result.getString(categoryIndex));
          feed.setFeedURL(result.getString(feedUrlIndex));
          feed.setSubscribed(result.getInt(subscribedIndex));

          category.add(feed);
          result.moveToNext();
        }
        categories.add(category);
        category = new ArrayList<Feed>();
      }
      result.close();
      db.close();

    } catch (SQLiteException exception) {
      Log.e(
          "NewsPaperTableHandler::getCategoriesForNewsPapers",
          "Categories could not be got " + exception.getMessage());
    } catch (Exception exception) {
      Log.e("NewsPaperTableHandler::getCategoriesForNewsPapers", exception.getMessage());
    }

    return categories;
  }
  /** @param ctx */
  public DBHelper(Context ctx) {
    myCtx = ctx;
    try {
      db = myCtx.openOrCreateDatabase(DATABASE_NAME, 0, null);

      // Check for the existence of the DBVERSION table
      // If it doesn't exist than create the overall data,
      // otherwise double check the version
      Cursor c =
          db.query(
              "sqlite_master",
              new String[] {"name"},
              "type='table' and name='" + TABLE_DBVERSION + "'",
              null,
              null,
              null,
              null);
      int numRows = c.getCount();
      if (numRows < 1) {
        CreateDatabase(db);
      } else {
        int version = 0;
        Cursor vc =
            db.query(
                true,
                TABLE_DBVERSION,
                new String[] {"version"},
                null,
                null,
                null,
                null,
                null,
                null);
        if (vc.getCount() > 0) {
          vc.moveToFirst();
          version = vc.getInt(0);
        }
        vc.close();
        if (version != DATABASE_VERSION) {
          needsUpgrade = true;
          Log.e(TAG, "database version mismatch");
        }
      }
      c.close();

    } catch (SQLException e) {
      Log.d(TAG, "SQLite exception: " + e.getLocalizedMessage());
    }
  }
Example #19
0
  @Override
  public void delete(String code) {
    String sql = null;
    SQLiteDatabase newlecDB =
        context.openOrCreateDatabase("newlecture", Context.MODE_PRIVATE, null);

    if (code.equals("") || code == null) {
      sql = "delete from Lectures";
      newlecDB.execSQL(sql);
    } else {
      sql = "delete from Lectures where code = ?";
      newlecDB.execSQL(sql, new String[] {code});
    }

    newlecDB.close();
  }
Example #20
0
  @Override
  public void insert(Lecture lecture) {
    SQLiteDatabase newlecDB =
        context.openOrCreateDatabase("newlecture", Context.MODE_PRIVATE, null);
    String sql = "insert into lectures values(?,?,?,?,?)";

    ContentValues values = new ContentValues();
    values.put("Code", lecture.getCode());
    values.put("Title", lecture.getTitle());
    values.put("Degree", lecture.getDegree());
    values.put("Price", lecture.getPrice());
    values.put("Image", "sam");

    newlecDB.insert("lectures", null, values);
    newlecDB.close();
  }
 public void displayCircles() {
   SQLiteDatabase db;
   db = mContext.openOrCreateDatabase("SpecApplicationDB", Context.MODE_PRIVATE, null);
   System.out.println(
       "///////////////////The Database table 'circle' content/////////////////////////");
   Cursor c = db.rawQuery("SELECT * FROM circle", null);
   while (c.moveToNext()) {
     System.out.println(
         "id="
             + c.getInt(0)
             + "-"
             + "appeartime="
             + c.getInt(1)
             + "-"
             + "desappeartime="
             + c.getInt(2)
             + "-"
             + "leftmargin="
             + c.getInt(3)
             + "-"
             + "rightmargin="
             + c.getInt(4)
             + "-"
             + "topmargin="
             + c.getInt(5)
             + "-"
             + "bottommargin="
             + c.getInt(6)
             + "-"
             + "height="
             + c.getInt(7)
             + "-"
             + "width="
             + c.getInt(8)
             + "-"
             + "videoid="
             + c.getInt(9));
   }
   c.close();
 }
Example #22
0
  @Override
  public Lecture getLecture(String code) {
    String sql = "SELECT * FROM Lectures where code =?";

    SQLiteDatabase newlecDB =
        context.openOrCreateDatabase("newlecture", Context.MODE_PRIVATE, null);
    Cursor cur = newlecDB.rawQuery(sql, new String[] {code});

    Lecture lecture = null;
    if (cur.moveToNext()) {
      lecture = new Lecture();
      lecture.setCode(cur.getString(0));
      lecture.setTitle(cur.getString(1));
      lecture.setDegree(cur.getString(2));
      lecture.setPrice(cur.getInt(3));
      lecture.setImage(BitmapFactory.decodeResource(context.getResources(), R.drawable.sam));
    }

    cur.close();
    newlecDB.close();

    return lecture;
  }
Example #23
0
  @Override
  public Database CreateDatabase(String dbName) {
    Database db = null;

    LOGGER.logOperationBegin("CreateDatabase", new String[] {"dbName"}, new Object[] {dbName});

    SQLiteDatabase sqlDB = null;
    try {
      Context context = AndroidServiceLocator.getContext();
      sqlDB = context.openOrCreateDatabase(dbName, Context.MODE_PRIVATE, null);
      if (!sqlDB.isOpen()) {
        return null;
      }
      db = new Database(dbName, DEFAULT_DATABASE_OPTION_COMPRESS, DEFAULT_DATABASE_OPTION_NEW);
    } catch (Exception ex) {
      LOGGER.logError("CreateDatabase", "Error", ex);
    } finally {
      closeDatabase(sqlDB);
      LOGGER.logOperationEnd("CreateDatabase", db);
    }

    return db;
  }
  public void populateTable() {
    ContentValues values = new ContentValues();

    try {
      db = appCtx.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);

      values.put("NewsPaperName", "Wall Street Journal");
      values.put("Category", "US Business");
      values.put("FeedURL", "http://online.wsj.com/xml/rss/3_7014.xml");
      values.put("Subscribed", 0);
      db.insert(tableName, null, values);

      values.put("NewsPaperName", "New York Times");
      values.put("Category", "Home Page US");
      values.put("FeedURL", "http://feeds.nytimes.com/nyt/rss/HomePage");
      values.put("Subscribed", 0);
      db.insert(tableName, null, values);

      db.close();
    } catch (SQLiteException exception) {
      Log.e("NewsPaperTableHandler::populateTable", "Could not populate the table");
    }
  }
 private void openDatabase() {
   cacheDatabase = context.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);
 }
Example #26
0
 CityDB(Context context, String path) {
   db = context.openOrCreateDatabase(CITY_DB_NAME, Context.MODE_PRIVATE, null);
 }
Example #27
0
 public UserDao(Context context) {
   db = context.openOrCreateDatabase(MyApp.DBNAME, Context.MODE_PRIVATE, null);
   if (ExistTable(db, SchemeCreator.USERTNAME) == false) {
     db.execSQL(SchemeCreator.getUTableSQL());
   }
 }
  /**
   * 初始化数据库
   *
   * @param context 上下文
   */
  void initDatabase(Context context) {
    SQLiteDatabase database =
        context.openOrCreateDatabase(dbName, Context.MODE_PRIVATE, null, null);

    /*获取当前数据库版本号*/
    int oldVersion = database.getVersion();
    if (showCreateLog) {
      LogUtils.createLog("获取本地数据库版本号:" + oldVersion);
      LogUtils.createLog("目标数据库版本号:" + version);
    }

    /*判断数据库版本,如果旧版本大于当前版本则抛出异常*/
    if (oldVersion > version) {
      throw new VLInitException("旧版本不能大于当前版本,旧版本为:" + oldVersion);
    }

    /*验证每个持久化对象信息实体;添加持久化实体至持久化实体表中;建立Update对象享元表;建立外键语句列表*/
    if (showCreateLog) {
      LogUtils.createLog("开始解析持久化对象信息实体");
    }
    Map<Class, Boolean> checkMap = new HashMap<>();
    Map<String, Update> updateMap = new HashMap<>();
    List<String> foreignSQL = new ArrayList<>();
    for (ReadEntity entity : entities) {
      Entity entitY = entity.analyzeEntity(checkMap, updateMap, foreignSQL, oldVersion);
      entityMap.put(entity.cls, entitY);

      if (showCreateLog) {
        LogUtils.createLog("持久化对象信息实体:" + entity.cls.getName() + " 完成解析");
      }
    }
    if (showCreateLog) {
      LogUtils.createLog("持久化对象信息实体解析完成");
    }

    /*判断数据库版本,如果版本相同则不做下列操作*/
    if (oldVersion == version) {

      if (showCreateLog) {
        LogUtils.createLog("版本相同,不执行建表与更新操作");
      }

      database.close();
      return;
    }

    /*遍历校验表,查看是否有外键是不存在的*/
    for (Class cls : checkMap.keySet()) {
      if (!checkMap.get(cls)) {
        throw new VLInitException(cls.getName() + "必须要在 XMl 文件中定义外键的 Entity 元素标签");
      }
    }
    if (showCreateLog) {
      LogUtils.createLog("外键合法性校验完成");
    }

    /*对持久化对象信息实体进行排序,排序规则为:
    1.无外键的优先于有外键
    2.两个有外键的,如果其中一个包含另一个,则包含者优先
    */
    Collections.sort(
        entities,
        new Comparator<ReadEntity>() {
          @Override
          public int compare(ReadEntity lhs, ReadEntity rhs) {
            if (lhs.foreignClass.size() == 0) return -1;
            else if (rhs.foreignClass.size() == 0) return 1;
            else if (lhs.foreignClass.contains(rhs.cls)) return 1;
            else if (rhs.foreignClass.contains(lhs.cls)) return -1;
            else return 0;
          }
        });

    /*建表并执行更新语句*/
    database.beginTransaction();

    if (showCreateLog) {
      LogUtils.createLog("执行建表与更新语句");
    }
    try {
      for (final ReadEntity entity : entities) {
        if (showCreateLog) {
          LogUtils.createLog("执行实体对象:" + entity.cls.getName());
          LogUtils.createLog("执行的SQL建表语句:" + entity.sql);
        }

        database.execSQL(entity.sql);

        for (UpdateEntity updateEntity : entity.updateEntityList) {
          if (showCreateLog) {
            LogUtils.createLog("执行更新对象:" + updateEntity.getClass().getName());
          }
          updateEntity.doUpdate(database);
        }
      }

      /*如果所有SQL成功执行,提交事务*/
      if (showCreateLog) {
        LogUtils.createLog("执行建表与更新语句成功!");
      }
      database.setTransactionSuccessful();
    } catch (SQLException e) {
      throw new VLInitException(e.getMessage());
    }

    database.endTransaction();

    /*更新完成后刷新数据库版本,关闭数据库*/
    if (showCreateLog) {
      LogUtils.createLog("设置当前数据库版本:" + version);
      LogUtils.createLog("创建日志结束");
    }
    database.setVersion(version);
    database.close();
  }
  public DatabaseManager(Context context) {
    setContext(this.context);

    setMyDB(context.openOrCreateDatabase(getDB_NAME(), context.MODE_PRIVATE, null));
  }
Example #30
0
 // 把上一次下载过的数据保存进数据库,关闭应用再进入时,不必重新请求连接
 public static SQLiteDatabase create(Context context, String dbname) {
   return context.openOrCreateDatabase(dbname, Context.MODE_PRIVATE, null);
 }