Android 引用外部数据库(一)
有现成的数据库,需要直接引入到项目中使用。
#准备
在开始之前我们要确认现有的数据库的表结构和字段信息等。(注意要看清楚数据库的大小,后面有用)
#第一步
将外部数据库拷贝到项目中的 assets文件夹中,如图
#第二步
在你要使用数据库之前将数据库拷贝到 /data/data/包名/databases/ 目录下。
代码
public static void copyDbFile(Context context, String db_name) { InputStream in = null; FileOutputStream out = null; //String path = "/data/data/" + context.getPackageName() + "/databases/"; File filePath = context.getDatabasePath(db_name); //spUtils 是为了防止多次拷贝 if (!SharePreferenceUtils.getBoolean(GlobalContent.COPE_SUCCESS,false)){ try { in = context.getAssets().open(db_name); // 从assets目录下复制 out = new FileOutputStream(filePath); int length = -1; byte[] buf = new byte[1024]; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); } out.flush(); SharePreferenceUtils.putBoolean(GlobalContent.COPE_SUCCESS,true); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e1) { e1.printStackTrace(); } } } }
#第三步
这时就可以开始查库了
SqlLiteHelper sqlLiteHelper = new SqlLiteHelper(getContext(), "mySql.db", null, 1); SQLiteDatabase readableDatabase = sqlLiteHelper.getReadableDatabase(); try { Cursor query = readableDatabase.query("message", new String[]{"_id", "message"}, null, null, null, null, null, limit); boolean b = query.moveToFirst(); while (!query.isLast()) { int id = query.getInt(query.getColumnIndex("_id")); String message = query.getString(query.getColumnIndex("message")); mDataList.add(new LoveMessageBean(id, message)); query.moveToNext(); } query.close(); Logger.i("mDataList : "+ mDataList.size()); }catch (Exception e){ UiUtils.showToast(getContext(),"error"); }
到这里已经成功的把外部数据库拷贝到项目中,并且开始 CRUD 了。
以上的方法,是做简单也是最原始的方法,之后会尝试使用第三方的工具来查询,如 GreenDao LitePal 等。
免责声明:本文内容由凌晨学院网转载自互联网,版权归原作者所有,凌晨学院网不拥有其著作权,亦不承担相应法律责任。如果本站侵犯了您的权益请及时联系team@lcwl.fun,核实后本站将会在2个工作日内对涉嫌侵权内容处理完毕!谢谢合作!