我试图使用sqlite帮助程序类,
我在/assets
文件夹中有我的db_map。
sqlite助手应该从那里复制到data/data/com.package.app/databases/
会发生什么事情,我得到FileNotFound exception
。
调试并使用assetManager.list("")
时。
我发现列表中有"images"
,"sounds"
,"webkit"
个文件。
奇怪的是,我没有这些,只有我的db_map
文件。
代码:
AssetManager assetManager = context.getResources().getAssets();
myInput = assetManager.open("db_map");
答案 0 :(得分:0)
首先 您需要在目标中创建数据库。之后你可以复制它的顶部。
因此。这就是我用的。
我创建了一个从SQLiteOpenHelper
扩展的类数据库在本课程中,我将执行以下操作。
// Database Version
private static final int DB_VERSION = 1;
// Database Name
private static String DB_NAME = "DB.sqlite";
//The default system path of your application database.
private static String DB_PATH = "/data/data/com.namespace.xxx/databases/";
public Database(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.myContext = context;
}
public void createDataBase() throws IOException{
Log.d(LOG, "Calling checkDataBase() Method");
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
Log.d(LOG, "!!!Database Found!!!");
}else{
//Empty database will be created into the default system path
Log.d(LOG, "!!!Creating Empy Database!!!");
this.getReadableDatabase();
this.close();
try {
Log.d(LOG, "!!!Coping Database!!!");
copyDataBase();
} catch (IOException e) {
throw new Error(e);
}
}
}
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
Log.d(LOG, "looking database at " + myPath);
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
Log.e(LOG, "Exception: database does not exist yet");
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
// Copies your database from your local assets-folder
// to the created empty database
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
Log.d(LOG, "Coping database from " + myInput + ", to " + outFileName);
//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();
}
祝你好运。