Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 如何在Android应用中使用已有的SQLite数据库

在我几个Android应用中,我需要访问已有的数据库。这些数据库往往很大,甚至超过asset文件大约1兆字节的限制。而且在新的版本中数据库需要更新。我在网上,特别是StackOverflow看了一些文章,并做了一些试验,觉得下面的代码能基本上满足我的需求。其主要思路是:1. 把数据库分解成几个asset文件。2. 当需要打开数据库时,如果数据库不存在,就把那几个asset文件重新合并成一个数据库文件。3. 如果数据库的版本改变了,就在onUpgrade()方法中把数据库文件删除掉。 下面是代码: //数据库的缺省路径private static finalString DB_PATH = "/data/data/com.mypackage.myapp/databases/";private static finalString DB_NAME = "mydb.db";private static finalint DB_VERSION = 2;private static finalString DB_SPLIT_NAME = "mydb.db.00";private static finalint DB_SPLIT_COUNT = 3;private SQLiteDatabasem_database;private final Contextm_context;/** * Constructor *保存传进来的context参数以用来访问应用的asset和资源文件。 * @param context */public MyDB(Contextcontext) { super(context, DB_NAME, null, DB_VERSION); this.m_context = context;}public static MyDBopenDatabaseReadOnly(Context context) { MyDB db = new MyDB(context);  try { db.createDataBase(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }  db.openDataBase(SQLiteDatabase.OPEN_READONLY); return db;}public static MyDBopenDatabaseReadWrite(Context context) { MyDB db = new MyDB(context);  try { db.createDataBase(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }  db.openDataBase(SQLiteDatabase.OPEN_READWRITE); return db;}/** *创建一个空数据库,用来存储你已有的数据库。 */public voidcreateDataBase() throws IOException{boolean dbExist =checkDataBase();if (dbExist) {  /*  **如果你的数据库的版本改变了,调用这个方法确保在onUpgrade()被调用时  **传进去的是可写的数据库。  */  SQLiteDatabase db =this.getWritableDatabase();  if (db != null) {   db.close(); } }  dbExist = checkDataBase();  if (!dbExist) { try {   /*   ** 调用这个方法以确保在缺省路径内产生一个空数据库,以便在其基础上复制我们已有的数据库。   */   SQLiteDatabase db =this.getReadableDatabase();    if (db != null) {     db.close();   }   copyDataBase(); } catch (IOException e) {   Log.e("DB", e.getMessage());      throw new Error("Error copyingdatabase");    }  }}/** * 检查数据库是否已存在,以避免重复复制。 * @return true if it exists, false if itdoesn"t */private static booleancheckDataBase(){ SQLiteDatabase checkDB = null;  try {   String path = DB_PATH + DB_NAME;   checkDB =SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e){   //database does"t exist yet. } if (checkDB != null) {   checkDB.close(); } return checkDB != null ? true : false;}/** * 把存在asset文件中的数据库复制的刚创建的空数据库中。 * */private voidcopyDataBase() throws IOException {  // 刚创建的空数据库的路径  String outFileName = DB_PATH + DB_NAME;  // 打开空数据库  OutputStream output = new FileOutputStream(outFileName);   byte[] buffer = new byte[1024*8];   AssetManager assetMgr =m_context.getAssets();   for (int i = 1; i <= DB_SPLIT_COUNT; i++){   // 打开分解的asset文件   String fn = DB_SPLIT_NAME +String.valueOf(i);   InputStream input = assetMgr.open(fn);   //Log.i("DB", "opened" + fn);    int length;   while ((length = input.read(buffer)) >0) {     //Log.i("DB", "read" + String.valueOf(length));     output.write(buffer, 0, length);     //Log.i("DB", "write" + String.valueOf(length));   }   input.close(); }  //Close the streams output.flush(); output.close();} /** * 打开数据库。 * */private voidopenDataBase(int flags) throws SQLException{  //Open the database  String myPath = DB_PATH + DB_NAME;  m_database =SQLiteDatabase.openDatabase(myPath, null, flags);} /** * 关闭数据库。 * */@Overridepublic synchronizedvoid close() {  if (m_database != null) m_database.close();    super.close();  }} @Overridepublic voidonCreate(SQLiteDatabase db) {  // 不需做任何事} /** * 在数据库版本提高时,删除原有数据库。 * */@Overridepublic voidonUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  if (newVersion > oldVersion) {   m_context.deleteDatabase(DB_NAME);  }}更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11