第一步:将数据库文件放入到assets目录中。注意Android studio需要将assets目录建在main项目下。即和Java,res等文件夹是同级的。
1.assets:不会在R.java文件下生成相应的标记,assets文件夹可以自己创建文件夹,必须使用AssetsManager类进行访问,存放到这里的资源在运行打包的时候都会打入程序安装包中,
2.res:会在R.java文件下生成标记,这里的资源会在运行打包操作的时候判断哪些被使用到了,没有被使用到的文件资源是不会打包到安装包中的。
res/raw和assets文件夹来存放不需要系统编译成二进制的文件,例如字体文件等
在res文件夹下还可以定义一下目录:
res/anim:这里存放的是动画资源。
res/xml:可以在Activity中使用getResource().getXML()读取这里的资源文件
res/raw:该目录下的文件可以直接复制到设备上,不能有子文件夹,编译软件时,这里的数据不需要编译,直接加入到程序安装包中,使用方法是getResource().OpenRawResources(ID),其中参数ID的形式是R.raw.XXX.
第二步:首次使用app,将assets目录下的数据库文件加载到android手机的sd下
/** * 见assets目录下的文件拷贝到sd上 * @return 存储数据库的地址 */ // 复制和加载区域数据库中的数据 public static String CopySqliteFileFromRawToDatabases(String SqliteFileName) throws IOException { // 第一次运行应用程序时,加载数据库到data/data/当前包的名称/database/<db_name> File dir = new File("data/data/" + MyApplication.getContext().getPackageName() + "/databases"); LogUtil.i("!dir.exists()=" + !dir.exists()); LogUtil.i("!dir.isDirectory()=" + !dir.isDirectory()); if (!dir.exists() || !dir.isDirectory()) { dir.mkdir(); } File file= new File(dir, SqliteFileName); InputStream inputStream = null; OutputStream outputStream =null; //通过IO流的方式,将assets目录下的数据库文件,写入到SD卡中。 if (!file.exists()) { try { file.createNewFile(); inputStream = MyApplication.getContext().getClass().getClassLoader().getResourceAsStream("assets/" + SqliteFileName); outputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len ; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) { outputStream.flush(); outputStream.close(); } if (inputStream != null) { inputStream.close(); } } } return file.getPath(); }
第三:不使用sd下的数据库文件。
/** * 获取全国的省份 * * @return */ public void getProvincesFromSQLite() { SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openDatabase(sqliePath, null, SQLiteDatabase.OPEN_READONLY); Cursor cursor = sqLiteDatabase.rawQuery("SELECT * from T_Province", null); provincesList.clear(); if (cursor.moveToFirst()) { do { String proSort = cursor.getString(cursor.getColumnIndex("ProSort")); String proName = cursor.getString(cursor.getColumnIndex("ProName")); provincesList.add(new Province(proSort,proName)); }while (cursor.moveToNext()); cursor.close(); } provinceAdapter.notifyDataSetChanged(); }