android程序复制数据库
一般项目中我们把db文件放到assert或者raw目录下面,在程序第一次启动的时候复制到私有目录下面
?
在使用过程中,老是发现复制不成功,私有目录下的db文件总是3072
?
<spanstyle="color:#ff0000;">后来发现应该是使用ContentProvider的原因,它会先创建一个空的db。
</span>
而我的程序在复制数据库的时候会判断私有目录下是否有数据库文件,如果有则不复制。
?
现在改为用SharedPreferences一个字段判断是否第一次复制。
<spanstyle="color:#ff0000;">第一次复制数据库的时候就算私有目录下有db文件,也删除。</span>
这样就ok了
?
代码如下:
public class CopyDataActivity extends Activity{ boolean needCopy = false; SharedPreferences mSP = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.copy_data); mSP = getSharedPreferences(Constants.PREFERENCES_NAME, MODE_PRIVATE); needCopy = mSP.getBoolean("need_copy_data", true); if(needCopy){ handler.post(copyPlanThread); }else{ goToMain(); } } private void goToMain(){ mSP.edit().putBoolean("need_copy_data", false).commit(); startActivity(new Intent(CopyDataActivity.this,LoginActivity.class)); this.finish(); } private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); int what = msg.what; int arg1 = msg.arg1; if(what==1){ //这里可以在页面显示复制进度什么的 Log.e("Copy","复制大小:"+arg1); }else{ goToMain(); mSP.edit().putBoolean("need_copy_data", false).commit(); } } }; Runnable copyPlanThread = new Runnable() { @Override public void run() { try{ copyDatabase(); }catch(Exception e){ e.printStackTrace(); } } }; private void copyDatabase() throws Exception{ Log.e("Copy","copy start"); File dbfile = new File(getFilesDir().getAbsolutePath() +File.separator+ "mydb.db"; File dir = dbfile.getParentFile(); if(dir.exists() == false){ dir.mkdirs(); } //把contentprovider生成的db删除 if(dbfile.exists()){ dbfile.delete(); } InputStream is = this.getResources().openRawResource(R.raw.library); FileOutputStream fos = new FileOutputStream( dbfile); byte[] buffer =new byte[1024]; int size = 0; int length = 0; //字节 while( (length= is.read(buffer)) > 0){ fos.write(buffer,0,length); size += length; Message msg = new Message(); msg.what = 1; msg.arg1 = size; handler.sendMessage(msg); } fos.flush(); fos.close(); is.close(); Log.e("Copy","copy end"); Message msg = new Message(); msg.what = 0; msg.arg1 = 0; handler.sendMessage(msg); } }
?
?
?
<ulstyle="display:none;">
<imgsrc='http://dl.iteye.com/upload/attachment/598512/8863f1d9-f38b-33f4-8262-dd5692375d79-thumb.jpg'class='magplus'title='点击查看原始大小图片'/>大小:14.3KB</ul>
查看图片附件相关推荐
lbyd0 2020-11-17
sushuanglei 2020-11-12
腾讯soso团队 2020-11-06
gaobudong 2020-11-04
yangkang 2020-11-09
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30