将开发的android app 安装到手机上后,如何在如见代码中替换手机上原有的数据库

如题所述

android sqlite数据库,第一次调用getWritableDatabase或者getReadableDatabase后,就会在程序的包下创建一个数据库,之前执行SQLiteOpenHelper的onCreate方法,
当数据库创建了以后,是不会再创建的,只有通过升级数据库版本号来实现
当数据库的版本号发生了变化以后,SQLiteOpenHelper会调用onUpgrade方法
因此都是在onUpgrade来处理新增字段,新增表等操作

要替换数据库
将原来数据库放到res/raw目录下,程序启动的时候,通过流读取了来,并写到你程序目录下
String dbfile = "/data"+ Environment.getDataDirectory().getAbsolutePath() + "/"+ context.getPackageName()+"数据库名"
InputStream is = context.getResources().openRawResource(R.raw.data);

FileOutputStream fos = new FileOutputStream(dbfile);
byte[] buffer = new byte[1024];
int count = 0;
while ((count =is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
fos.flush();
}
fos.close();
is.close();
这样就把数据库给替换了,但是通常不建议这么做
最好是在onUpgrade来处理

请采纳哈追问

 
  if(!new File("/sdcard/imedia/healthmate.db").exists()) {
  File tempFile1=new File("/sdcard/imedia");
  if (!tempFile1.isDirectory())
  {
  tempFile1.mkdirs();
  }
后面就和你那个差不多
  

追答

你必须要知道你的数据库名,和创建的位置,这样就可以替换了

温馨提示:答案为网友推荐,仅供参考
相似回答