一般项目中我们把db文件放到assert或者raw目录下面,在程序第一次启动的时候复制到私有目录下面
?
在使用过程中,老是发现复制不成功,私有目录下的db文件总是3072
?
<span style="color: #ff0000;">
后来发现应该是使用ContentProvider的原因,它会先创建一个空的db。
</span>
<br><img src="http://dl.iteye.com/upload/attachment/598512/8863f1d9-f38b-33f4-8262-dd5692375d79.jpg" alt="">
而我的程序在复制数据库的时候会判断私有目录下是否有数据库文件,如果有则不复制。
?
现在改为用SharedPreferences一个字段判断是否第一次复制。
<span style="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);
}
}
?
?
?
<ul style="display:none;">
<img src='http://dl.iteye.com/upload/attachment/598512/8863f1d9-f38b-33f4-8262-dd5692375d79-thumb.jpg' class='magplus' title='点击查看原始大小图片' />
大小: 14.3 KB
</ul>