最近在学习androidSQLite数据库加载时,遇到了一些问题:
1.我在虚拟机外面创建的数据库文件,如何复制到虚拟机里面?(不是通过DDMS来复制,而是用程序)?
2.继承SQLiteOpenHelper类的子类,其中的OnCreate()重载方法到底是在什么情况下运行的?
第一个问题,我的解决方案如下:
在继承SQLiteOpenHelper的子类SQLiteHelp中,新建函数createDatabase:
private void createDatabase(Context mContext) { // 输出路径 String outFileName = DB_PATH + DB_NAME; // 检测/创建数据库的文件夹 File dir = new File(DB_PATH); if (!dir.exists()) { dir.mkdir(); } // 如果文件夹已经存在了 else { // 检查文件是否存在 dir = new File(DB_PATH, DB_NAME); if (dir.exists()) return; } InputStream input = null; OutputStream output = null; // 从资源中读取数据库流 input = mContext.getResources().openRawResource(R.raw.driving_assistant); try { output = new FileOutputStream(outFileName); // 拷贝到输出流 byte[] buffer = new byte[2048]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭输出流 try { output.flush(); output.close(); } catch (IOException e) { } // 关闭输入流 try { input.close(); } catch (IOException e) { } } }
在构造函数中调用createDatabase函数,可以解决第一个问题
注意,不能放在重载的方法OnCreate()中,当你第一次运行程序后,再次运行时,OnCreate函数不会运行
我试着故意删掉虚拟器中的数据库文件,如果你把函数放在OnCreate()中,运行会出错
第二个问题有待解决