在Android中创建和打开数据库

时间:2013-09-23 01:48:34

标签: android sql database sqlite

我通过从已创建的 sqlite 数据库加载数据创建了我的 Android 数据库,并将其从资源管理器复制到android创建的数据库中。

这是我的数据库助手类的代码。

public class DataBaseHelper extends SQLiteOpenHelper{

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

    private static String DB_NAME = "myDBName";

    private SQLiteDatabase myDataBase; 

    private final Context myContext;

    public DataBaseHelper(Context context) {

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

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

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

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

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

    }

}

我现在尝试在createDatabase()方法中调用onCreate()方法。当我然后安装并运行我的应用程序并尝试通过调用openDatabase()打开数据库时,它会记录消息并抛出空指针异常 到数据库实例变量,意味着它无法打开它。但是当我从数据库助手类的构造函数或其他类调用createDatabase()时,它可以工作。我不知道为什么会这样。

1 个答案:

答案 0 :(得分:0)

没有看到堆栈跟踪,很难说......但需要检查几件事情:

  1. 确保数据库中有一个android_metadata表,其中包含语言环境字段(例如,值为“我的”为“en_US”)。

  2. 当您的应用创建数据库时,会自动为您/您的应用设置rw-rw权限。建议您检查要复制到/databases目录的数据库。

  3. (最有可能的问题):与上面的数字2类似,检查文件/组所有权属性并确保将它们分配给您的应用。如果不是,则可以通过chown [your app's UID] : [your app's UID] /[PATH TO YOUR DATABASE FILE](commandLine)方法在运行时执行Runtime.getRuntime().exec来执行此操作。