Пример #1
0
	//该函数是在第一次创建数据库的时候执行,实际上是在第一次得到SQLiteDatabse对象的时候,才会调用这个方法
	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.d("databasehelp", db.getPath());

		//execSQL函数用于执行SQL语句 根据表明name创建,可以利用发射动态创建,目前先写死测试创建数据库
		db.execSQL(createSql);
	}
Пример #2
0
  @Override
  public void onClick(View v) {
    if (v.getId() == R.id.btnSaveDB) {
      // they've hit apply.
      OnChange(); // make sure we've got everything.

      File fDirectory = new File(MakeParentPath());
      if (!fDirectory.exists() && !fDirectory.mkdir()) {
        Toast.makeText(this, "Couldn't create directory.  Not saved", Toast.LENGTH_LONG).show();
      } else {
        File f = new File(MakeFilePath(m_strTargetFilename));
        if (f.exists()) {
          Toast.makeText(this, "File already exists.  Not saved", Toast.LENGTH_LONG).show();
        } else {
          SQLiteDatabase db = RaceDatabase.Get();
          db.beginTransaction();

          String strDBPath = db.getPath();
          try {
            if (CopyFile(new File(strDBPath), f)) {
              Toast.makeText(this, "DB Saved", Toast.LENGTH_LONG).show();
            } else {
              Toast.makeText(this, "DB failed to save", Toast.LENGTH_LONG).show();
            }
          } catch (IOException e) {
            Toast.makeText(this, "Failed to copy DB: " + e.toString(), Toast.LENGTH_LONG).show();
          } catch (Exception e) {
            Toast.makeText(this, "Unexpected failure: " + e.toString(), Toast.LENGTH_LONG).show();
          }

          db.endTransaction();
        }
      }
    }
  }
Пример #3
0
 /** Closes a previously opened database connection. */
 public void closeDatabase() {
   if (mDatabase != null) {
     mDatabase.close();
     Timber.d("closeDatabase, database %s closed = %s", mDatabase.getPath(), !mDatabase.isOpen());
     mDatabase = null;
   }
 }
Пример #4
0
  /**
   * @param context the {@link Context} to use.
   * @return the db.
   * @throws IOException if something goes wrong.
   */
  public SQLiteDatabase getDatabase(Context context) throws IOException {
    File databaseFile;
    try {
      databaseFile = ResourcesManager.getInstance(context).getDatabaseFile();
    } catch (Exception e) {
      throw new IOException(e.getLocalizedMessage());
    }
    if (databaseHelper == null || !databaseFile.exists()) {

      databaseHelper = new DatabaseOpenHelper(databaseFile);

      SQLiteDatabase db = databaseHelper.getWritableDatabase(context);
      if (GPLog.LOG_ANDROID) {
        Log.i(DEBUG_TAG, "Database: " + db.getPath());
        Log.i(DEBUG_TAG, "Database Version: " + db.getVersion());
        Log.i(DEBUG_TAG, "Database Page Size: " + db.getPageSize());
        Log.i(DEBUG_TAG, "Database Max Size: " + db.getMaximumSize());
        Log.i(DEBUG_TAG, "Database Open?  " + db.isOpen());
        Log.i(DEBUG_TAG, "Database readonly?  " + db.isReadOnly());
        Log.i(DEBUG_TAG, "Database Locked by current thread?  " + db.isDbLockedByCurrentThread());
      }
    }

    return databaseHelper.getWritableDatabase(context);
  }
Пример #5
0
 @Override
 public void onOpen(SQLiteDatabase sqLiteDatabase) {
   if (L)
     Log.d(
         Tag,
         "onOpen SQLiteDatabase: " + "Db: " + sqLiteDatabase.toString() + sqLiteDatabase.isOpen());
   if (!sqLiteDatabase.isOpen())
     SQLiteDatabase.openDatabase(sqLiteDatabase.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
 }
Пример #6
0
 @Inject
 public OrmdroidPersister(Context context, SearchOptions searchOptions) {
   this.searchOptions = searchOptions;
   ORMDroidApplication.initialize(context);
   //		ORMDroidApplication.
   SQLiteDatabase database = ORMDroidApplication.getDefaultDatabase();
   Ln.d("database: " + database.getPath());
   //		ORMDroidApplication.getSingleton().enableLoggingVerbose(true);
 }
  // 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.");
    }
  }
Пример #8
0
  protected void runArchive() {

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    // TODO: add check to make sure this is not empty
    File dbFile = new File(db.getPath());
    db.close();
    if (archive.add(dbFile)) {
      dbFile.delete();
    }
    reloadDbHelper(manager);
    db = databaseHelper.getWritableDatabase(); // Build new database
    db.close();
  }
Пример #9
0
 @Override
 public SQLiteDatabase openOrCreateDatabase(
     final String name, final int mode, final SQLiteDatabase.CursorFactory factory) {
   final SQLiteDatabase result =
       SQLiteDatabase.openOrCreateDatabase(this.getDatabasePath(name), null);
   // SQLiteDatabase result = super.openOrCreateDatabase(name, mode,
   // factory);
   if (Log.isLoggable(DatabaseContext.DEBUG_CONTEXT, Log.WARN)) {
     Log.w(
         DatabaseContext.DEBUG_CONTEXT,
         "openOrCreateDatabase(" + name + ",,) = " + result.getPath());
   }
   return result;
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.submenu_settings);

    mListView = (ListView) findViewById(android.R.id.list);
    mInflater = getLayoutInflater();

    SubMenuDBHelper hlp = new SubMenuDBHelper(this);
    mDatabase = hlp.getWritableDatabase();

    Log.d("SubMenuSettings", "Loaded db " + mDatabase.getPath());

    dlg = ProgressDialog.show(this, "Please wait...", "Loading applications...");

    InsertAllApps();

    refreshCursor();

    refreshMenuList(mDatabase);

    dlg.cancel();

    Log.d("SubMenuSettings", "Count: " + mCursorSubMenus.getCount());

    mListView.setOnCreateContextMenuListener(
        new OnCreateContextMenuListener() {
          public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

            refreshMenuList(mDatabase);

            menu.add(0, mnuMoveItem, 0, "Add to main menu");

            int i = 1;
            while (mCursorSubMenus.moveToNext()) {
              menu.add(
                  0,
                  mnuMoveItem + i,
                  0,
                  "Add to submenu "
                      + mCursorSubMenus.getString(mCursorSubMenus.getColumnIndex("name")));
              i++;
            }
          }
        });
  }
Пример #11
0
  // creates a local copy of db file from the working path in assets
  private final boolean setupLocalDB(String dbFileName) {
    // private class for help creating database file in setupLocalDB()
    class DBHelper extends SQLiteOpenHelper {
      public DBHelper(Context context, String name) {
        super(context, name, null, 1);
      }

      @Override
      public void onCreate(SQLiteDatabase db) {}

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
    };

    try {
      // Open then close a SQLite database to prepare for copying
      DBHelper dbHelper = new DBHelper(assetsContext, dbFileName);
      SQLiteDatabase db = dbHelper.getReadableDatabase();
      localDbPath = db.getPath();
      db.close();
      dbHelper.close();

      // Open the empty db as the output stream
      OutputStream localDb = new FileOutputStream(localDbPath);

      // Open your local db as the input stream
      InputStream dbAsset = assetsContext.getAssets().open(workingPath + dbFileName);

      // transfer bytes from dbAsset to localDb
      byte[] buffer = new byte[1024];
      int length;
      while ((length = dbAsset.read(buffer)) > 0) localDb.write(buffer, 0, length);

      // Close the streams
      dbAsset.close();
      localDb.flush();
      localDb.close();
    } catch (Exception e) {
      e.printStackTrace();
      localDbPath = null; // reset to null if failed
      return false;
    }

    return true;
  }
Пример #12
0
  /*
   * used during development to copy database to external storage so we can access it via DDMS
   */
  private void copyDatabase(SQLiteDatabase db) {
    String copyFrom = db.getPath();
    String copyTo =
        WordPress.getContext().getExternalFilesDir(null).getAbsolutePath() + "/" + DB_NAME;

    try {
      InputStream input = new FileInputStream(copyFrom);
      OutputStream output = new FileOutputStream(copyTo);

      byte[] buffer = new byte[1024];
      int length;
      while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
      }

      output.flush();
      output.close();
      input.close();
    } catch (IOException e) {
      AppLog.e(T.DB, "failed to copy reader database", e);
    }
  }
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (BuildConfig.DEBUG) {
      Log.d(LOGCAT, String.format("Upgrading from %1$d  to %2$d", oldVersion, newVersion));
    }

    try {
      String currentDbFile = db.getPath();
      createDatabaseBackupOnUpgrade(currentDbFile, oldVersion);
    } catch (Exception ex) {
      ExceptionHandler handler = new ExceptionHandler(getContext());
      handler.handle(ex, "creating database backup, can't continue");

      // don't upgrade
      return;
    }

    // update databases
    updateDatabase(db, oldVersion, newVersion);

    // notify sync about the db update.
    new SyncManager(getContext()).dataChanged();
  }
Пример #14
0
 /** @return The full path to this database file. */
 public String getPath() {
   return mDatabase.getPath();
 }
  /**
   * 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();
      }
    }
  }
Пример #16
0
 @Override
 public String toString() {
   return "DatabaseFileArchive [mDatabase=" + mDatabase.getPath() + "]";
 }
 @Test
 public void testGetPath() throws Exception {
   assertThat(database.getPath())
       .isEqualTo(Robolectric.application.getDatabasePath("path").getPath());
 }