日期:2014-05-16  浏览次数:20371 次

android sqlite外部数据库迁移
最近开发碰到需要加载商品牌子和商品型号的listview功能,算上型号有5 000多条记录,用string.xml 或者web service代价够大。解决方案是导入外部db文件到应用文件中,通过查询获取速度还是可以,listview在cursor上已经自带支持了分页延迟查询。

首先在网上看了看例子,大部分的方案都是把db文件放在raw包内,然后通过转移到android 模拟器内存内,也是目前想到的较为合理方案。

首先通过以下代码将数据库文件迁移
public boolean extractDatabase(String dbfile) {
		try {
			if (new File(dbfile).exists()) {
				return true;
			}
			InputStream is = this.context.getResources().openRawResource(
					R.raw.models);
			try {
				FileOutputStream fos = new FileOutputStream(dbfile);
				try {
					byte[] buffer = new byte[BUFFER_SIZE];
					int count = 0;
					while ((count = is.read(buffer)) > 0) {						
						fos.write(buffer, 0, count);
						fos.flush();
					}
				} finally {
					fos.close();
				}
			} finally {
				is.close();
			}
			return true;
		} catch (FileNotFoundException e) {
			Log.e("Database", "File not found");
		} catch (IOException e) {
			Log.e("Database", "IO exception");
		}
		return false;
	}

然后通过打开数据库文件来获取Sqlitedatabase实例
sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(
					DB_LOCATION, null);
sqLiteDatabase.rawQuery(expression, params);

即可查询获取Cursor数据
注:在拷文件过程中,发现在部分AVD版本会出现buffer不够的问题,原因是db文件在拷贝过程中会被解压,从而占用内存,无法成功完成拷贝。后来的方案比较偏,通过将db文件重命名为mp3文件,然后拷为db文件。很可行,mp3文件属于音频压缩格式,可以躲过android的解压过程。有更好的办法,欢迎留言交流