不知怎的,我在Log中复制.db文件时遇到错误(如您在代码中看到的那样) napoleon.db文件位于assets文件夹中,因此我认为一切都应该有效,但它并没有
为什么没有找到它?
我是通过示例来做的,但它并不起作用。 有什么想法吗?
public class MySqLiteOpenHelper extends SQLiteOpenHelper{
private static String DATABASE_NAME = "napoleon.db";
public final static String DATABASE_PATH = "/data/data/com.example.task/databases/";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase dataBase;
private final Context dbContext;
public MySqLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.dbContext = context;
// checking database and open it if exists
if (checkDataBase()) {
openDataBase();
} else
{
try {
this.getReadableDatabase();
copyDataBase();
this.close();
openDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
Toast.makeText(context, "Initial database is created", Toast.LENGTH_LONG).show();
}
}
private void copyDataBase() throws IOException{
InputStream myInput = dbContext.getAssets().open(DATABASE_NAME);
String outFileName = DATABASE_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String dbPath = DATABASE_PATH + DATABASE_NAME;
dataBase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
boolean exist = false;
try {
String dbPath = DATABASE_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(dbPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
Log.v("MyLog", "database does't exist");
}
if (checkDB != null) {
exist = true;
checkDB.close();
}
return exist;
}
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
您应该使用此DB路径:
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
对于Jellybean 4.2多用户更改:
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
为:
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
答案 1 :(得分:-1)
使用以下帖子逐行学习将数据库从资产复制到应用程序内存
http://iamvijayakumar.blogspot.in/2013/11/copy-sqlite-database-file-from-assets.html