我知道为了访问设备上的数据文件夹,它需要被植根。但是,如果我只想将数据库从资产文件夹复制到设备上的数据文件夹,那么复制过程是否可以在无根手机上运行?以下是我的数据库助手类。从 logcat 中,我可以验证调用 copyDataBase()、createDataBase() 和 openDataBase() 的方法是否成功返回。但是,我收到此错误消息
android.database.sqlite.SQLiteException:没有这样的表:TABLE_NAME:
当我的应用程序正在执行 rawQuery。我怀疑数据库文件没有成功复制(不能太确定,因为我无权访问数据文件夹),但是对 copyDatabase() 的方法调用没有抛出任何异常。会是什么呢?谢谢。
ps:我的设备还没有root,希望不是报错的主要原因。
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
String s = new Boolean(dbExist).toString();
Log.d("dbExist", s );
if(dbExist){
//do nothing - database already exist
Log.d("createdatabase","DB exists so do nothing");
}else{
this.getReadableDatabase();
try {
copyDataBase();
Log.d("copydatabase","Successful return frm method call!");
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase(){
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = null;
myInput = myContext.getAssets().open(DB_NAME);
Log.d("copydatabase","InputStream successful!");
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
/* @Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}*/
public void close() {
// NOTE: openHelper must now be a member of CallDataHelper;
// you currently have it as a local in your constructor
if (myDataBase != null) {
myDataBase.close();
}
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}