Расширенный класс SQLiteOpenHelper каждый раз вызывает onCreate? - PullRequest
1 голос
/ 06 декабря 2011
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 даже не должен вызываться.Что здесь происходит?

Ответы [ 2 ]

3 голосов
/ 06 декабря 2011

попробуй это у меня работает

     /**
   * 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();

}
2 голосов
/ 06 декабря 2011

Вы не должны переопределять 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...