1
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "test.db";
    private static final int DB_VERSION = 1;
    private boolean DB_JUST_CREATED = false;

    private Context _context;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        _context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("WOD", "onCreate firing");
        DB_JUST_CREATED = true;
    }

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

    }

    @Override
    public synchronized SQLiteDatabase getWritableDatabase() {
        SQLiteDatabase db = super.getWritableDatabase();

        // Copy db from assets folder if db was just created.
        if(DB_JUST_CREATED == true) {
            Log.d("WOD", "Creating db");
            try {
                // Open InputStream to assets db.
                InputStream inStream = _context.getAssets().open(DB_NAME);

                // Open OutputStream to new db.
                OutputStream outStream = new FileOutputStream(db.getPath());

                //transfer bytes from the input-file to the output-file
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inStream.read(buffer)) > 0)
                {
                    outStream.write(buffer, 0, length);
                }

                //Close the streams
                outStream.flush();
                outStream.close();
                inStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return db;
    }

}

いくつかの異なるアクティビティで DatabaseHelper オブジェクトを作成しようとしましたが、毎回同じで、onCreate()が起動され、新しいデータベースが作成されます。DDMS ファイル エクスプローラーを確認したところ、確かに、アプリケーションを強制停止しても、データベースは作成後もそこにとどまるため、onCreate を呼び出すことさえできません。何が起きてる?

4

2 に答える 2

3

これらを試してみてください

     /**
   * Creates a empty database on the system and rewrites it with your own
   * database.
   * */
public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();

    if (dbExist) {
        // do nothing - database already exist
    } else {

        // By calling this method and empty database will be created into
        // the default system path
        // of your application so we are gonna be able to overwrite that
        // database with our database.
        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }

}

/**
 * Check if the database already exist to avoid re-copying the file each
 * time you open the application.
 * 
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase() {

    SQLiteDatabase checkDB = null;

    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {
        Log.v("DB", "No DB");
        // database does't exist yet.

    }

    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException {

    // Open your local db as the input stream
    InputStream myInput = myContext.getResources().openRawResource(
            R.raw.diary_database);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}
于 2011-12-06T17:19:11.383 に答える
2

getWritableDatabaseそのような方法でスーパークラス メソッドをオーバーライドして呼び出すべきではありません。

ここでそのメソッドがカバーの下で何をするかを見てみましょう: http://codesearch.google.com/codesearch#uX1GffpyOZk/core/java/android/database/sqlite/SQLiteOpenHelper.java&q=package:android.git.kernel.org %20file:android/database/sqlite/SQLiteOpenHelper.java&l=1

アセットからファイルをコピーした後、SQLite データベースのユーザー バージョンが現在のバージョンに設定されていることを確認して、実装onCreateへの後続の呼び出しで呼び出されないようにする必要があります。getWritableDatabase

db = _context.openOrCreateDatabase(DB_NAME, 0, null);
db.setVersion(DB_VERSION);
于 2011-12-06T17:29:41.410 に答える