在Android中使用现有数据库时,onCreate方法是否仍会被调用?

时间:2016-04-21 06:27:38

标签: android

BUMP EDIT。

我对Android比较新,所以请原谅这个问题是否容易,但是我试图将现有数据库导入我的程序,并使用链接中提到的方法 http://blog.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ How to use an existing database with an Android application

现在,如果我想在我的数据库中添加其他表,如果我将它们放在代码的Oncreate部分,它们仍然可以工作还是我必须将它们放在代码的openDatabase / createDatabase部分? 我使用的代码是:

 public class DatabaseHelper extends SQLiteOpenHelper{

        //The Android's default system path of your application database.
        private static String DB_PATH = "/data/data/com.example.az101.conquer_the_word/databases/";

        private static String DB_NAME = "words.sqlite";

        private SQLiteDatabase myDataBase;
        private final Context myContext;
        /**static final String dbName="words";
        static final String employeeTable="Employees";
        static final String colID="EmployeeID";
        static final String colName="EmployeeName";
        static final String colAge="Age";
        static final String colDept="Dept";

        static final String deptTable="Dept";
        static final String colDeptID="DeptID";
        static final String colDeptName="DeptName";

        static final String viewEmps="ViewEmps";**/
        /**
         * Constructor
         * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
         * @param context
         */
        public DatabaseHelper(Context context) {

            super(context, DB_NAME, null, 1);
            this.myContext = context;
        }

        /**
         * 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){

                //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.getAssets().open(DB_NAME);

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

        }

        public void openDataBase() throws SQLException{

            //Open the database
            String myPath = DB_PATH + DB_NAME;
            myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }

        @Override
        public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

        }

        private static final String TAG = DatabaseHelper.class.getSimpleName().toString();


        @Override
        public void onCreate(SQLiteDatabase db) {
            //All necessary tables you like to create will create here
            db.execSQL(ScoreTableRepo.createTable());
            db.execSQL(Users_in_groupsRepo.createTable());
            db.execSQL(Groups_infoRepo.createTable());
            db.execSQL(ClustersRepo.createTable());
            db.execSQL(Words_StatsRepo.createTable());

        }

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


            Log.d(TAG, String.format("SQLiteDatabase.onUpgrade(%d -> %d)", oldVersion, newVersion));

            // Drop table if existed, all data will be gone!!!
            db.execSQL("DROP TABLE IF EXISTS " + ScoreTable.TABLE);
            db.execSQL("DROP TABLE IF EXISTS " + Users_In_Groups.TABLE);
            db.execSQL("DROP TABLE IF EXISTS " + Groups_info.TABLE);
            db.execSQL("DROP TABLE IF EXISTS " + Clusters.TABLE);
            db.execSQL("DROP TABLE IF EXISTS " + Words_Stats.TABLE);

            onCreate(db);
        }

    }



        // Add your public helper methods to access and get content from the database.
        // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
        // to you to create adapters for your views.

另外为了防止多个查询在代码中产生问题的问题,我使用下面提供的方法来保留一个计数器,我不确定如果我做得对,我将如何以及何时调用databaseManager函数?我的数据库管理器的代码也在下面给出。 https://github.com/dmytrodanylyk/dmytrodanylyk/blob/gh-pages/articles/Concurrent%20Database%20Access.md

public class DatabaseManager {
private Integer mOpenCounter = 0;

private static DatabaseManager instance;
private static SQLiteOpenHelper mDatabaseHelper;
private SQLiteDatabase mDatabase;

public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
    if (instance == null) {
        instance = new DatabaseManager();
        mDatabaseHelper = helper;
    }
}

public static synchronized DatabaseManager getInstance() {
    if (instance == null) {
        throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
                " is not initialized, call initializeInstance(..) method first.");
    }

    return instance;
}

public synchronized SQLiteDatabase openDatabase() {
    mOpenCounter+=1;
    if(mOpenCounter == 1) {
        // Opening new database
        mDatabase = mDatabaseHelper.getWritableDatabase();
    }
    return mDatabase;
}

public synchronized void closeDatabase() {
    mOpenCounter-=1;
    if(mOpenCounter == 0) {
        // Closing database
        mDatabase.close();

    }
}

}

感谢任何输入和帮助。

Oncreate方法中的repofunctions具有与该特定表相关的所有函数。我无法在网上找到任何正确的方法链接。

1 个答案:

答案 0 :(得分:0)

SqliteOpenHelper:管理数据库创建和版本管理的助手类。

SqliteOpenHelper -> OnCreate()
在第一次创建数据库时调用。这是表的创建和表的初始填充的地方。

请参阅文档:http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#onCreate(android.database.sqlite.SQLiteDatabase)