android - 扩展的 SQLiteOpenHelper 类每次都调用 onCreate 吗?

标签 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;
    }

}

我已经尝试在几个不同的 Activity 中创建一个 DatabaseHelper 对象,每次都是一样的,onCreate() 被触发,然后它创建一个新的数据库。我检查了 DDMS 文件资源管理器,果然,数据库在创建后仍然存在,即使我强行停止应用程序,所以甚至不应该调用 onCreate。这是怎么回事?

最佳答案

尝试这些对我有用

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

}

关于android - 扩展的 SQLiteOpenHelper 类每次都调用 onCreate 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8403915/

相关文章:

sqlite - Android Studio 搜索现有的 sqlite 数据库

Android:在调试器断点时,由于 ANR,dalvik 杀死应用程序

android - 如何从 AOSP 构建库?

python-2.7 - Python sqlite3 Column1 val 的 Column 2 val 等于数字,并且 val 等于另一个数字

java - SQLite 插入时出现空指针异常

android - SQLiteDatabase.update 不影响行

java - AsyncTask 和回调 Android

android - 如何在android中更改EditText提示颜色

Swift SQLite3 语法和绑定(bind)

javascript - 如何在 Webkit 浏览器中用 Javascript 编写自定义 SQLite 函数?