此活动执行的操作是将数据库从assets文件夹复制到applications数据库文件夹(如果应用程序是第一次运行)。但是数据库只有在应用程序第二次运行后才会被复制!
package fifth3.sem;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
@SuppressWarnings("unused")
public class Splash extends Activity {
static DBAdapter db;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String destPath="/data/data/"+getPackageName()+"/databases/cryptdb2zx";
File f=new File(destPath);
File f2=new File("emptyfile");
if(!f2.exists()){
//do nothing
{
try {
Log.w("akash", "file does not exist");
CopyDB(getBaseContext().getAssets().open("cryptdb2"),new FileOutputStream(destPath));
f2.createNewFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
db=new DBAdapter(this);
db.open();
Thread t=new Thread(){
public void run()
{
try{
for(int i=0;i<5;i++){
Thread.sleep(1000);
}
}
catch(Exception e){
}
finally{
startActivity(new Intent("login.screen"));
}
}
};
t.start();
}
public void CopyDB(InputStream inputStream,OutputStream outputStream)throws IOException{
Log.w("akash", "copying");
byte[] buffer=new byte[1024];
int length;
while((length=inputStream.read(buffer))>0){
outputStream.write(buffer,0,length);
}
inputStream.close();
outputStream.close();
Log.w("akash", "copied");
}}
发布于 2011-10-12 01:55:32
如果没有看到您的数据库适配器,我就不能确定,因为您试图在目录存在之前复制数据库,所以第一次它很可能无法工作。通常,如果数据库不存在,数据库适配器将创建一个数据库。这将创建“数据库”目录。因此,当您打开新安装的应用程序时,该目录不存在,复制失败。然而,在复制逻辑之后,您立即创建了一个db适配器,它(可能)创建了db (以及包含它的目录)。因此,第二次运行时,复制是成功的。
这应该像你想要的那样运行(重要的是顺序):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db=new DBAdapter(this);
db.open();
String destPath="/data/data/"+getPackageName()+"/databases/cryptdb2zx";
File f=new File(destPath);
File f2=new File("emptyfile");
if(!f2.exists()){
//do nothing
{
try {
Log.w("akash", "file does not exist");
CopyDB(getBaseContext().getAssets().open("cryptdb2"),new FileOutputStream(destPath));
f2.createNewFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}https://stackoverflow.com/questions/7729309
复制相似问题