我正在尝试将我的数据库从assets-folder复制到数据库文件夹,但它无法正常工作我也尝试了很多不同的解决方案,但我没有成功......
我的代码&错误日志如下:
错误日志
Main.java
import android.app.Activity;
import android.os.Bundle;
public class Main extends Activity {
private DB db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db=new DB(this);
db.database();
}
}
DB.java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DB extends SQLiteOpenHelper {
public final String path="data/data/com.example.databasetest/databases/";
public final String Name="dbkala";
public SQLiteDatabase mydb;
private final Context mycontext;
public DB(Context context) {
super(context, "dbkala", null, 1);
mycontext=context;
}
@Override
public void onCreate(SQLiteDatabase arg0) {
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
public void database(){
boolean checkdb=checkdb();
if(checkdb){
}else{
this.getReadableDatabase();
try{
copydatabase();
}catch(IOException e){
}
}
}
public void open(){
mydb=SQLiteDatabase.openDatabase(path+Name, null,SQLiteDatabase.OPEN_READWRITE);
}
public void close(){
mydb.close();
}
public boolean checkdb(){
SQLiteDatabase db=null;
try{
db=SQLiteDatabase.openDatabase(path+Name, null,SQLiteDatabase.OPEN_READONLY);
}
catch(SQLException e)
{
}
return db !=null ? true:false ;
}
public void copydatabase() throws IOException{
OutputStream myOutput = new FileOutputStream(path+Name);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = mycontext.getAssets().open(Name);
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
}