Exemplo n.º 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;
  }
Exemplo n.º 2
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_student);

    update_no = (TextView) findViewById(R.id.deleteNoView);
    update_name = (EditText) findViewById(R.id.et_name_update);
    update_grade = (EditText) findViewById(R.id.et_grade_update);
    update_callNum = (EditText) findViewById(R.id.et_callNum_update);
    updateOkBtn = (Button) findViewById(R.id.updateOkBtn);
    gotoListBtn = (Button) findViewById(R.id.listgoBtn_update);

    mDatabase = openOrCreateDatabase("students.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);

    mDatabase.setLocale(Locale.getDefault()); // 기본 지역
    mDatabase.setLockingEnabled(true); // 스레드에 락 설정
    mDatabase.setVersion(3); // 버전 설정

    update_no.setText(getInfo());
    update_name.setText(getInfo1());
    update_grade.setText(getInfo2());
    update_callNum.setText(getInfo3());

    updateOkBtn.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            ContentValues values = new ContentValues();
            values.put("name", update_name.getText().toString());
            values.put("grade", update_grade.getText().toString());
            values.put("callnum", update_callNum.getText().toString());

            int result =
                mDatabase.update(
                    "students", values, "_id=?", new String[] {update_no.getText().toString()});

            Log.i("testLog", "update result>>>" + result);
            Toast.makeText(getApplicationContext(), "행 수정 성공", Toast.LENGTH_SHORT).show();

            update_name.setText("");
            update_grade.setText("");
            update_callNum.setText("");
          }
        });

    gotoListBtn.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            Intent listintent = new Intent(Update_Student.this, List_Students.class);
            startActivity(listintent);
          }
        });
  }
 @Override
 protected void setUp() throws Exception {
   super.setUp();
   mDatabaseFile = new File("/sqlite_stmt_journals", "database_test.db");
   if (mDatabaseFile.exists()) {
     mDatabaseFile.delete();
   }
   mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null);
   assertNotNull(mDatabase);
   mDatabase.setVersion(CURRENT_DATABASE_VERSION);
 }
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    File dbDir = getContext().getDir("tests", Context.MODE_PRIVATE);
    mDatabaseFile = new File(dbDir, "database_test.db");

    if (mDatabaseFile.exists()) {
      mDatabaseFile.delete();
    }
    mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null);
    assertNotNull(mDatabase);
    mDatabase.setVersion(CURRENT_DATABASE_VERSION);
  }
Exemplo n.º 5
0
    /**
     * Create the db from scratch.
     *
     * @param context the context to use.
     * @throws IOException if something goes wrong.
     */
    public void create(Context context) throws IOException {
      db.setLocale(Locale.getDefault());
      db.setVersion(DATABASE_VERSION);

      // CREATE TABLES
      GPLog.createTables(db);
      DaoMetadata.createTables();
      DaoMetadata.initProjectMetadata(null, null, null, null);
      DaoNotes.createTables();
      DaoGpsLog.createTables();
      DaoBookmarks.createTables();
      DaoImages.createTables();
    }
Exemplo n.º 6
0
 @Override
 public void onCreate(SQLiteDatabase db) {
   for (String table : _builder.getTables()) {
     String sqlStr = null;
     try {
       sqlStr = _builder.getSQLCreate(table);
     } catch (DataAccessException e) {
       EvtLog.e(this.getClass().getName(), e);
     }
     if (sqlStr != null) db.execSQL(sqlStr);
   }
   db.setVersion(_version);
 }
Exemplo n.º 7
0
 private static void upgradeCacheDatabase() {
   int oldVersion = mCacheDatabase.getVersion();
   if (oldVersion != 0) {
     Log.i(
         LOGTAG,
         "Upgrading cache database from version "
             + oldVersion
             + " to "
             + DATABASE_VERSION
             + ", which will destroy all old data");
   }
   mCacheDatabase.execSQL("DROP TABLE IF EXISTS cache");
   mCacheDatabase.setVersion(CACHE_DATABASE_VERSION);
 }
Exemplo n.º 8
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.delete_student);

    deleteNo = (TextView) findViewById(R.id.noView_delete);
    deleteName = (TextView) findViewById(R.id.nameView_delete);
    deleteGrade = (TextView) findViewById(R.id.gradeView_delete);
    deleteCallNum = (TextView) findViewById(R.id.callNumView_delete);

    deleteOkBtn = (Button) findViewById(R.id.DeleteOkBtn);
    listOkBtn = (Button) findViewById(R.id.gotoListBtn_delete);

    mDatabase = openOrCreateDatabase("students.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);

    mDatabase.setLocale(Locale.getDefault()); // 기본 지역
    mDatabase.setLockingEnabled(true); // 스레드에 락 설정
    mDatabase.setVersion(3); // 버전 설정

    deleteNo.setText(getInfo());
    deleteName.setText(getInfo1());
    deleteGrade.setText(getInfo2());
    deleteCallNum.setText(getInfo3());

    deleteOkBtn.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            int result =
                mDatabase.delete("students", "_id=?", new String[] {deleteNo.getText().toString()});
            Log.i("testLog", "delete result>>>" + result);
            Toast.makeText(getApplicationContext(), "행 삭제 성공", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(Delete_Student.this, List_Students.class);
            startActivity(intent);
          }
        });
    listOkBtn.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            Intent intent = new Intent(Delete_Student.this, List_Students.class);
            startActivity(intent);
          }
        });
  }
Exemplo n.º 9
0
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   try {
     db.execSQL("DROP TABLE IF EXISTS img");
     db.execSQL("DROP TABLE IF EXISTS thumb");
     db.execSQL("DROP TABLE IF EXISTS imgup");
     db.execSQL("DROP TABLE IF EXISTS user");
     db.execSQL("DROP TABLE IF EXISTS favor");
     db.execSQL("DROP TABLE IF EXISTS follow");
     db.execSQL(CREATE_TABLE_THUMB);
     db.execSQL(CREATE_TABLE_IMG);
     db.execSQL(CREATE_TABLE_IMG_UP);
     db.execSQL(CREATE_TABLE_USER);
     db.execSQL(INSERT_TABLE_USER);
     db.execSQL(CREATE_TABLE_FAVOR);
     db.execSQL(CREATE_TABLE_FOLLOW);
     db.execSQL(CREATE_TABLE_USER_LIST);
   } catch (Exception e) {
     e.printStackTrace();
   }
   db.setVersion(newVersion);
 }
Exemplo n.º 10
0
  private void createTable() {
    mDatabase.execSQL(
        "CREATE TABLE "
            + HTTPAUTH_TABLE_NAME
            + " ("
            + ID_COL
            + " INTEGER PRIMARY KEY, "
            + HTTPAUTH_HOST_COL
            + " TEXT, "
            + HTTPAUTH_REALM_COL
            + " TEXT, "
            + HTTPAUTH_USERNAME_COL
            + " TEXT, "
            + HTTPAUTH_PASSWORD_COL
            + " TEXT,"
            + " UNIQUE ("
            + HTTPAUTH_HOST_COL
            + ", "
            + HTTPAUTH_REALM_COL
            + ") ON CONFLICT REPLACE);");

    mDatabase.setVersion(DATABASE_VERSION);
  }
Exemplo n.º 11
0
 public void openDataBase() throws SQLiteException {
   db = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
   db.setVersion(DB_VERSION);
   needsUpgrade = false;
 }
  /**
   * 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 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();
      }
    }
  }
Exemplo n.º 13
0
  /** function to pass the timer limit and user log to the class to calculate score */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test2);

    TextView sit = (TextView) findViewById(R.id.test222textView1);
    Typeface font1 = Typeface.createFromAsset(getAssets(), "CANDARA.TTF");
    sit.setTypeface(font1);
    Bundle bundle = getIntent().getExtras();
    final String s = bundle.getString("un");
    final int g = bundle.getInt("un1");
    final long ter = g * 1000;
    // Toast.makeText(getApplicationContext(),String.valueOf(g),Toast.LENGTH_LONG).show();
    qb1 = (Button) findViewById(R.id.qbutton1);
    ctr = (TextView) findViewById(R.id.ctr);
    // timer code
    TimerTask task =
        new TimerTask() {
          @Override
          public void run() {
            elapsed += INTERVAL;
            if (elapsed >= ter) {

              this.cancel();
              vend();
              displayText("Time Up!!");
              // boolean ab=qb1.performClick();
              return;
            }
            displayText("Time: " + (ter - elapsed) / 1000);
          }
        };

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(task, INTERVAL, INTERVAL);

    TextView tt1 = (TextView) findViewById(R.id.test2textView2);
    r1 = (RadioButton) findViewById(R.id.option1);
    r2 = (RadioButton) findViewById(R.id.option2);
    r3 = (RadioButton) findViewById(R.id.option3);

    Random randomGenerator = new Random();
    Random randomGenerator2 = new Random();

    int a = randomGenerator.nextInt(866);
    String quest;
    final String ans1;
    String ans2, ans3;

    // Toast.makeText(getApplicationContext(),String.valueOf(a) , Toast.LENGTH_LONG).show();
    /** opening the database */
    SQLiteDatabase db;
    db = openOrCreateDatabase("vocab.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
    db.setVersion(1);
    db.setLocale(Locale.getDefault());
    db.setLockingEnabled(true);
    Cursor cur = db.query("words", null, null, null, null, null, null);
    Cursor cur2 = db.query("tes", null, null, null, null, null, null);
    cur.moveToFirst();
    cur2.moveToFirst();
    TextView ty = (TextView) findViewById(R.id.testindex);
    ty.append(cur2.getString(1));
    ty.append(".");
    cur.moveToPosition(a);
    quest = cur.getString(2);
    ans1 = cur.getString(1);
    cur.moveToPosition((a + 1) % 867);
    ans2 = cur.getString(1);
    cur.moveToPosition((a + 2) % 867);
    ans3 = cur.getString(1);
    tt1.setText(quest);
    r1.setClickable(true);
    r2.setClickable(true);
    r3.setClickable(true);

    int b = randomGenerator2.nextInt(3);
    // Toast.makeText(getApplicationContext(), String.valueOf(b),Toast.LENGTH_LONG).show();
    /** shuffling the answer */
    if (b == 0) {
      r1.setText(ans1);
      r2.setText(ans2);
      r3.setText(ans3);
    } else if (b == 1) {
      r1.setText(ans3);
      r2.setText(ans1);
      r3.setText(ans2);
    } else if (b == 2) {
      r1.setText(ans2);
      r2.setText(ans3);
      r3.setText(ans1);
    }

    qb1.setOnClickListener(
        new OnClickListener() {

          public void onClick(View v) {
            int tep = 0, tep2;
            /** opening the database */
            SQLiteDatabase db;
            db = openOrCreateDatabase("vocab.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
            db.setVersion(1);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            ContentValues values = new ContentValues();
            Cursor cur2 = db.query("tes", null, null, null, null, null, null);
            cur2.moveToFirst();
            /** check for user answer */
            String uans = "";

            if (r1.isChecked() == true) {
              uans = r1.getText().toString();

            } else if (r2.isChecked() == true) {
              uans = r2.getText().toString();

            } else if (r3.isChecked() == true) {
              uans = r3.getText().toString();
            }
            /** updation of the database with respect to the user selection of answer */

            /** action script when the user's answer is correct */
            if (uans.equals(ans1)) {
              tep = Integer.parseInt(cur2.getString(0));
              tep2 = Integer.parseInt(cur2.getString(1));
              tep++;
              tep2++;
              values.put("score", tep);
              values.put("count", tep2);
              db.update("tes", values, "ven=?", new String[] {"11"});

            }
            /** action script when the answer is wrong */
            else {
              /** printing the right answer when the user's answer is wrong */
              Toast.makeText(
                      getApplicationContext(), "The right answer : " + ans1, Toast.LENGTH_SHORT)
                  .show();

              tep2 = Integer.parseInt(cur2.getString(1));
              tep2++;
              values.put("count", tep2);
              db.update("tes", values, "ven=?", new String[] {"11"});
            }

            //	Toast.makeText(getApplicationContext(), String.valueOf(tep),
            // Toast.LENGTH_LONG).show();
            //	Toast.makeText(getApplicationContext(), String.valueOf(tep2),
            // Toast.LENGTH_LONG).show();

            /** moving to result1 class after the quiz gets over to calculate score */
            if (tep2 == 16) {
              Intent i = new Intent(Test2.this, Result1.class);
              Bundle bundle = new Bundle();
              bundle.putString("un", s);
              i.putExtras(bundle);
              startActivity(i);
              finish();
            }
            /** generating different questions */
            else {
              /** intent that defines the action after the last question */
              Intent i = new Intent(Test2.this, Test2.class);
              Bundle bundle = new Bundle();
              bundle.putString("un", s);
              bundle.putInt("un1", g);
              i.putExtras(bundle);
              startActivity(i);
              finish();
            }
          }
        });
    db.close();
  }
  /**
   * 初始化数据库
   *
   * @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();
  }
Exemplo n.º 15
0
  private static void upgradeDatabase() {
    int oldVersion = mDatabase.getVersion();
    if (oldVersion != 0) {
      Log.i(
          LOGTAG,
          "Upgrading database from version "
              + oldVersion
              + " to "
              + DATABASE_VERSION
              + ", which will destroy old data");
    }
    boolean justPasswords = 8 == oldVersion && 9 == DATABASE_VERSION;
    boolean justAuth = 9 == oldVersion && 10 == DATABASE_VERSION;
    if (justAuth) {
      mDatabase.execSQL("DROP TABLE IF EXISTS " + mTableNames[TABLE_HTTPAUTH_ID]);
      mDatabase.execSQL(
          "CREATE TABLE "
              + mTableNames[TABLE_HTTPAUTH_ID]
              + " ("
              + ID_COL
              + " INTEGER PRIMARY KEY, "
              + HTTPAUTH_HOST_COL
              + " TEXT, "
              + HTTPAUTH_REALM_COL
              + " TEXT, "
              + HTTPAUTH_USERNAME_COL
              + " TEXT, "
              + HTTPAUTH_PASSWORD_COL
              + " TEXT,"
              + " UNIQUE ("
              + HTTPAUTH_HOST_COL
              + ", "
              + HTTPAUTH_REALM_COL
              + ") ON CONFLICT REPLACE);");
      return;
    }

    if (!justPasswords) {
      mDatabase.execSQL("DROP TABLE IF EXISTS " + mTableNames[TABLE_COOKIES_ID]);
      mDatabase.execSQL("DROP TABLE IF EXISTS cache");
      mDatabase.execSQL("DROP TABLE IF EXISTS " + mTableNames[TABLE_FORMURL_ID]);
      mDatabase.execSQL("DROP TABLE IF EXISTS " + mTableNames[TABLE_FORMDATA_ID]);
      mDatabase.execSQL("DROP TABLE IF EXISTS " + mTableNames[TABLE_HTTPAUTH_ID]);
    }
    mDatabase.execSQL("DROP TABLE IF EXISTS " + mTableNames[TABLE_PASSWORD_ID]);

    mDatabase.setVersion(DATABASE_VERSION);

    if (!justPasswords) {
      // cookies
      mDatabase.execSQL(
          "CREATE TABLE "
              + mTableNames[TABLE_COOKIES_ID]
              + " ("
              + ID_COL
              + " INTEGER PRIMARY KEY, "
              + COOKIES_NAME_COL
              + " TEXT, "
              + COOKIES_VALUE_COL
              + " TEXT, "
              + COOKIES_DOMAIN_COL
              + " TEXT, "
              + COOKIES_PATH_COL
              + " TEXT, "
              + COOKIES_EXPIRES_COL
              + " INTEGER, "
              + COOKIES_SECURE_COL
              + " INTEGER"
              + ");");
      mDatabase.execSQL(
          "CREATE INDEX cookiesIndex ON " + mTableNames[TABLE_COOKIES_ID] + " (path)");

      // formurl
      mDatabase.execSQL(
          "CREATE TABLE "
              + mTableNames[TABLE_FORMURL_ID]
              + " ("
              + ID_COL
              + " INTEGER PRIMARY KEY, "
              + FORMURL_URL_COL
              + " TEXT"
              + ");");

      // formdata
      mDatabase.execSQL(
          "CREATE TABLE "
              + mTableNames[TABLE_FORMDATA_ID]
              + " ("
              + ID_COL
              + " INTEGER PRIMARY KEY, "
              + FORMDATA_URLID_COL
              + " INTEGER, "
              + FORMDATA_NAME_COL
              + " TEXT, "
              + FORMDATA_VALUE_COL
              + " TEXT,"
              + " UNIQUE ("
              + FORMDATA_URLID_COL
              + ", "
              + FORMDATA_NAME_COL
              + ", "
              + FORMDATA_VALUE_COL
              + ") ON CONFLICT IGNORE);");

      // httpauth
      mDatabase.execSQL(
          "CREATE TABLE "
              + mTableNames[TABLE_HTTPAUTH_ID]
              + " ("
              + ID_COL
              + " INTEGER PRIMARY KEY, "
              + HTTPAUTH_HOST_COL
              + " TEXT, "
              + HTTPAUTH_REALM_COL
              + " TEXT, "
              + HTTPAUTH_USERNAME_COL
              + " TEXT, "
              + HTTPAUTH_PASSWORD_COL
              + " TEXT,"
              + " UNIQUE ("
              + HTTPAUTH_HOST_COL
              + ", "
              + HTTPAUTH_REALM_COL
              + ") ON CONFLICT REPLACE);");
    }
    // passwords
    mDatabase.execSQL(
        "CREATE TABLE "
            + mTableNames[TABLE_PASSWORD_ID]
            + " ("
            + ID_COL
            + " INTEGER PRIMARY KEY, "
            + PASSWORD_HOST_COL
            + " TEXT, "
            + PASSWORD_USERNAME_COL
            + " TEXT, "
            + PASSWORD_PASSWORD_COL
            + " TEXT,"
            + " UNIQUE ("
            + PASSWORD_HOST_COL
            + ", "
            + PASSWORD_USERNAME_COL
            + ") ON CONFLICT REPLACE);");
  }
Exemplo n.º 16
0
  /** Creating any table that missing and upgrading necessary tables. */
  private static SQLiteDatabase upgradeDB(SQLiteDatabase mMetaDb, int databaseVersion) {
    Timber.i("MetaDB:: Upgrading Internal Database..");
    // if (mMetaDb.getVersion() == 0) {
    Timber.i("MetaDB:: Applying changes for version: 0");

    if (mMetaDb.getVersion() < 4) {
      mMetaDb.execSQL("DROP TABLE IF EXISTS languages;");
      mMetaDb.execSQL("DROP TABLE IF EXISTS customDictionary;");
      mMetaDb.execSQL("DROP TABLE IF EXISTS whiteboardState;");
    }

    // Create tables if not exist
    mMetaDb.execSQL(
        "CREATE TABLE IF NOT EXISTS languages ("
            + " _id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + "did INTEGER NOT NULL, ord INTEGER, "
            + "qa INTEGER, "
            + "language TEXT)");
    mMetaDb.execSQL(
        "CREATE TABLE IF NOT EXISTS whiteboardState ("
            + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + "did INTEGER NOT NULL, "
            + "state INTEGER)");
    mMetaDb.execSQL(
        "CREATE TABLE IF NOT EXISTS customDictionary ("
            + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + "did INTEGER NOT NULL, "
            + "dictionary INTEGER)");
    mMetaDb.execSQL(
        "CREATE TABLE IF NOT EXISTS intentInformation ("
            + "id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + "fields TEXT NOT NULL)");
    mMetaDb.execSQL(
        "CREATE TABLE IF NOT EXISTS smallWidgetStatus ("
            + "id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + "progress INTEGER NOT NULL, left INTEGER NOT NULL, eta INTEGER NOT NULL)");
    // Use pragma to get info about widgetStatus.
    Cursor c = mMetaDb.rawQuery("PRAGMA table_info(widgetStatus)", null);
    int columnNumber = c.getCount();
    if (columnNumber > 0) {
      if (columnNumber < 7) {
        mMetaDb.execSQL(
            "ALTER TABLE widgetStatus " + "ADD COLUMN eta INTEGER NOT NULL DEFAULT '0'");
        mMetaDb.execSQL(
            "ALTER TABLE widgetStatus " + "ADD COLUMN time INTEGER NOT NULL DEFAULT '0'");
      }
    } else {
      mMetaDb.execSQL(
          "CREATE TABLE IF NOT EXISTS widgetStatus ("
              + "deckId INTEGER NOT NULL PRIMARY KEY, "
              + "deckName TEXT NOT NULL, "
              + "newCards INTEGER NOT NULL, "
              + "lrnCards INTEGER NOT NULL, "
              + "dueCards INTEGER NOT NULL, "
              + "progress INTEGER NOT NULL, "
              + "eta INTEGER NOT NULL)");
    }
    c = mMetaDb.rawQuery("PRAGMA table_info(intentInformation)", null);
    columnNumber = c.getCount();
    if (columnNumber > 2) {
      mMetaDb.execSQL(
          "ALTER TABLE intentInformation " + "ADD COLUMN fields INTEGER NOT NULL DEFAULT '0'");
      mMetaDb.execSQL(
          "ALTER TABLE intentInformation " + "DROP COLUMN source INTEGER NOT NULL DEFAULT '0'");
      mMetaDb.execSQL(
          "ALTER TABLE intentInformation " + "DROP COLUMN target INTEGER NOT NULL DEFAULT '0'");
    }
    mMetaDb.setVersion(databaseVersion);
    Timber.i("MetaDB:: Upgrading Internal Database finished. New version: %d", databaseVersion);
    return mMetaDb;
  }
Exemplo n.º 17
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final SQLiteDatabase db;

    db = openOrCreateDatabase("TestingData.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
    db.setVersion(1);
    db.setLocale(Locale.getDefault());
    db.setLockingEnabled(true);

    final String CREATE_TABLE_COURSES =
        "CREATE TABLE IF NOT EXISTS courses ("
            + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "course_name TEXT,"
            + "course_tutor TEXT,"
            + "course_summary TEXT"
            + ");";
    final String CREATE_TABLE_STUDENTS =
        "CREATE TABLE IF NOT EXISTS students ("
            + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "student_name TEXT,"
            + "student_rollno INTEGER NOT NULL , "
            + "student_location TEXT,"
            + "student_email TEXT,"
            + "student_phone INT"
            + ");";
    final String CREATE_TABLE_CS =
        "CREATE TABLE IF NOT EXISTS cs ("
            + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "student_id INTEGER NOT NULL CONSTRAINT "
            + "student_id REFERENCES students(student_rollno) "
            + "ON DELETE CASCADE,"
            + "course_id NOT NULL CONSTRAINT "
            + "course_id REFERENCES courses(course_name) "
            + "ON DELETE CASCADE,"
            + "grade TEXT,"
            + "sem TEXT"
            + ");";

    //        if(flag==0)
    //        {
    //        	db.execSQL("DROP TABLE IF EXISTS courses");
    //        	db.execSQL("DROP TABLE IF EXISTS students");
    //        	db.execSQL("DROP TABLE IF EXISTS cs");
    //        	flag=1;
    //        }

    db.execSQL(CREATE_TABLE_COURSES);
    db.execSQL(CREATE_TABLE_STUDENTS);
    db.execSQL(CREATE_TABLE_CS);

    final String CREATE_TRIGGER_STUDENTS =
        "CREATE TRIGGER IF NOT EXISTS fk_cs_studentid "
            + " BEFORE INSERT "
            + " ON cs"
            + " FOR EACH ROW BEGIN"
            + " SELECT CASE WHEN ((SELECT id  FROM students"
            + "  WHERE id=new.student_id ) IS NULL)"
            + " THEN RAISE (ABORT,'Foreign Key Violation') END;"
            + "  END;";
    final String CREATE_TRIGGER_COURSES =
        "CREATE TRIGGER IF NOT EXISTS fk_cs_courseid "
            + " BEFORE INSERT "
            + " ON cs"
            + " FOR EACH ROW BEGIN"
            + " SELECT CASE WHEN ((SELECT id  FROM courses"
            + "  WHERE id=new.course_id ) IS NULL)"
            + " THEN RAISE (ABORT,'Foreign Key Violation') END;"
            + "  END;";
    db.execSQL(CREATE_TRIGGER_COURSES);
    db.execSQL(CREATE_TRIGGER_STUDENTS);

    final Context context = getApplicationContext();

    Button b1 = (Button) findViewById(R.id.button1);
    //       Log.v("uhuh","asdjasld");
    b1.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Auto-generated method stub
            Button addstud = (Button) v;
            Intent i = new Intent(context, student_details.class);
            startActivity(i);
          }
        });

    Button b2 = (Button) findViewById(R.id.button2);
    b2.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Auto-generated method stub
            Button addstud = (Button) v;
            Intent i = new Intent(context, course_details.class);
            startActivity(i);
          }
        });

    Button b3 = (Button) findViewById(R.id.button3);
    b3.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Auto-generated method stub
            Button addstud = (Button) v;
            Intent i = new Intent(context, register.class);
            startActivity(i);
          }
        });

    Button b4 = (Button) findViewById(R.id.resetdb);
    b4.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Auto-generated method stub
            Button addstud = (Button) v;
            db.execSQL("DROP TABLE IF EXISTS courses");
            db.execSQL("DROP TABLE IF EXISTS students");
            db.execSQL("DROP TABLE IF EXISTS cs");

            db.execSQL(CREATE_TABLE_COURSES);
            db.execSQL(CREATE_TABLE_STUDENTS);
            db.execSQL(CREATE_TABLE_CS);
          }
        });

    Button b5 = (Button) findViewById(R.id.upgrade_button);
    b5.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Auto-generated method stub
            Button addstud = (Button) v;
            Intent i = new Intent(context, upgrade.class);
            startActivity(i);
          }
        });

    Button b6 = (Button) findViewById(R.id.report_button);
    b6.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Auto-generated method stub
            Button addstud = (Button) v;
            Intent i = new Intent(context, get_report.class);
            startActivity(i);
          }
        });
  }
Exemplo n.º 18
0
  private SQLiteDatabase createV50Database() {

    SQLiteDatabase db =
        RuntimeEnvironment.application.openOrCreateDatabase(
            databaseFile.getName(), Context.MODE_PRIVATE, null);

    String[] v50SchemaSql =
        new String[] {
          "CREATE TABLE folders (id INTEGER PRIMARY KEY, name TEXT, last_updated INTEGER, unread_count INTEGER,"
              + "visible_limit INTEGER, status TEXT, push_state TEXT, last_pushed INTEGER,"
              + "flagged_count INTEGER default 0, integrate INTEGER, top_group INTEGER, poll_class TEXT,"
              + "push_class TEXT, display_class TEXT, notify_class TEXT);",
          "CREATE TABLE messages (id INTEGER PRIMARY KEY, deleted INTEGER default 0, folder_id INTEGER, uid TEXT,"
              + "subject TEXT, date INTEGER, flags TEXT, sender_list TEXT, to_list TEXT, cc_list TEXT,"
              + "bcc_list TEXT, reply_to_list TEXT, html_content TEXT, text_content TEXT,"
              + "attachment_count INTEGER, internal_date INTEGER, message_id TEXT, preview TEXT,"
              + "mime_type TEXT, normalized_subject_hash INTEGER, empty INTEGER, read INTEGER default 0,"
              + "flagged INTEGER default 0, answered INTEGER default 0, forwarded INTEGER default 0);",
          "CREATE TABLE headers (id INTEGER PRIMARY KEY, message_id INTEGER, name TEXT, value TEXT);",
          "CREATE TABLE threads (id INTEGER PRIMARY KEY, message_id INTEGER, root INTEGER, parent INTEGER);",
          "CREATE TABLE attachments (id INTEGER PRIMARY KEY, message_id INTEGER,store_data TEXT,"
              + "content_uri TEXT, size INTEGER, name TEXT, mime_type TEXT,"
              + "content_id TEXT, content_disposition TEXT);",
          "CREATE TABLE pending_commands (id INTEGER PRIMARY KEY, command TEXT, arguments TEXT);",
          "CREATE INDEX folder_name ON folders (name);",
          "CREATE INDEX header_folder ON headers (message_id);",
          "CREATE INDEX msg_uid ON messages (uid, folder_id);",
          "CREATE INDEX msg_folder_id_deleted_date ON messages (folder_id,deleted,internal_date);",
          "CREATE INDEX msg_empty ON messages (empty);",
          "CREATE INDEX msg_read ON messages (read);",
          "CREATE INDEX msg_flagged ON messages (flagged);",
          "CREATE INDEX msg_composite ON messages (deleted, empty,folder_id,flagged,read);",
          "CREATE INDEX threads_message_id ON threads (message_id);",
          "CREATE INDEX threads_root ON threads (root);",
          "CREATE INDEX threads_parent ON threads (parent);",
          "CREATE TRIGGER set_thread_root AFTER INSERT ON threads BEGIN "
              + "UPDATE threads SET root=id WHERE root IS NULL AND ROWID = NEW.ROWID; END;",
          "CREATE TRIGGER delete_folder BEFORE DELETE ON folders BEGIN "
              + "DELETE FROM messages WHERE old.id = folder_id; END;",
          "CREATE TRIGGER delete_message BEFORE DELETE ON messages BEGIN "
              + "DELETE FROM attachments WHERE old.id = message_id;"
              + "DELETE FROM headers where old.id = message_id; END;"
        };
    for (String statement : v50SchemaSql) {
      db.execSQL(statement);
    }
    db.setVersion(50);

    String[] folderSql =
        new String[] {
          "INSERT INTO folders VALUES (1,'Trash',0,NULL,25,NULL,NULL,0,0,0,1,'NO_CLASS','INHERITED','FIRST_CLASS','INHERITED')",
          "INSERT INTO folders VALUES (2,'Sent',1448975758597,NULL,25,NULL,'uidNext=552',NULL,0,0,1,'NO_CLASS','INHERITED','FIRST_CLASS','INHERITED')",
          "INSERT INTO folders VALUES (8,'Drafts',0,NULL,25,NULL,NULL,0,0,0,1,'FIRST_CLASS','INHERITED','FIRST_CLASS','INHERITED')",
          "INSERT INTO folders VALUES (13,'Spam',NULL,NULL,25,NULL,NULL,NULL,0,0,1,'NO_CLASS','INHERITED','FIRST_CLASS','INHERITED')",
          "INSERT INTO folders VALUES (14,'K9MAIL_INTERNAL_OUTBOX',NULL,NULL,25,NULL,NULL,NULL,0,0,1,'NO_CLASS','INHERITED','FIRST_CLASS','INHERITED')",
          "INSERT INTO folders VALUES (15,'K9mail-errors',NULL,NULL,25,NULL,NULL,NULL,0,0,1,'NO_CLASS','INHERITED','FIRST_CLASS','INHERITED')",
          "INSERT INTO folders VALUES (16,'dev',1453812012958,NULL,25,NULL,'uidNext=9',0,0,0,0,'INHERITED','SECOND_CLASS','NO_CLASS','INHERITED')",
        };
    for (String statement : folderSql) {
      db.execSQL(statement);
    }

    return db;
  }
Exemplo n.º 19
0
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bet);

    TextView sit = (TextView) findViewById(R.id.bettitle);
    Typeface font1 = Typeface.createFromAsset(getAssets(), "CANDARA.TTF");
    sit.setTypeface(font1);

    /** opening the database */
    SQLiteDatabase db;
    db = openOrCreateDatabase("vocab.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
    db.setVersion(1);
    db.setLocale(Locale.getDefault());
    db.setLockingEnabled(true);
    Cursor cur = db.query("profiles", null, null, null, null, null, null);
    cur.moveToFirst();

    /** populating the array with the list of users available */
    String[] pro = new String[cur.getCount()];
    if (cur.getCount() > 0) {
      pro = new String[cur.getCount()];
      int i = 0;
      do {
        pro[i] = cur.getString(1);
        i++;
      } while (cur.moveToNext());
    }
    cur.close();
    db.close();

    final AutoCompleteTextView textview =
        (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, pro);
    textview.setAdapter(adapter);
    /** moving to the create profile class */
    Button bun2 = (Button) findViewById(R.id.betbutton1);
    bun2.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            Intent i = new Intent(Bet.this, Newuser.class);
            startActivity(i);
            finish();
          }
        });

    /** authenticating the user and taking him to his home page */
    Button bun1 = (Button) findViewById(R.id.betbutton2);
    bun1.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            String stt = textview.getText().toString();
            SQLiteDatabase db;
            db = openOrCreateDatabase("vocab.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
            db.setVersion(1);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            Cursor cur = db.query("profiles", null, null, null, null, null, null);
            cur.moveToFirst();
            int y = 0;
            /** moving to the test class */
            while (cur.isAfterLast() == false) {
              if (cur.getString(1).equals(stt)) {
                y = 11;

                Intent navi = new Intent(Bet.this, Test1.class);
                Bundle bundle = new Bundle();
                bundle.putString("un", stt);
                navi.putExtras(bundle);
                startActivity(navi);
                finish();
                break;
              } else {
                cur.moveToNext();
              }
            }
            cur.close();
            db.close();
            if (y != 11) {
              Toast.makeText(
                      getApplicationContext(), "User Name does not exist!", Toast.LENGTH_LONG)
                  .show();
            }
          }
        });

    /** actionscript for the autocomplete textview */
    textview.setOnItemClickListener(
        new OnItemClickListener() { // int i=1;

          @Override
          public void onItemClick(AdapterView<?> adapter, View view, int pos, long arg3) {
            String st = adapter.getItemAtPosition(pos).toString();
            SQLiteDatabase db;
            db = openOrCreateDatabase("vocab.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
            db.setVersion(1);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            Cursor cur = db.query("profiles", null, null, null, null, null, null);
            cur.moveToFirst();
            int x = 0;
            /** authenticating process */
            while (cur.isAfterLast() == false) {
              if (cur.getString(1).equals(st)) {
                x = 11;
                Intent navi = new Intent(Bet.this, Test1.class);
                Bundle bundle = new Bundle();
                bundle.putString("un", st);
                navi.putExtras(bundle);
                startActivity(navi);
                finish();
                break;
              } else {
                cur.moveToNext();
              }
            }
            cur.close();
            db.close();
            if (x != 11) {
              Toast.makeText(
                      getApplicationContext(), "User Name does not exist!", Toast.LENGTH_LONG)
                  .show();
            }
          }
        });
  }
 @Test
 public void shouldSetAndGetVersion() throws Exception {
   assertThat(database.getVersion()).isEqualTo(0);
   database.setVersion(20);
   assertThat(database.getVersion()).isEqualTo(20);
 }