扩展的SQLiteOpenHelper类每次调用onCreate?

时间:2011-12-06 17:12:25

标签: android sqlite sqliteopenhelper

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 个答案:

答案 0 :(得分: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();

}

答案 1 :(得分: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);