【发布时间】:2011-11-08 14:50:08
【问题描述】:
我尝试从 assets 目录中复制 SQLite 数据库以便稍后访问它。但我做不到!
public class DatabaseAdapter {
private static String DB_PATH = "/data/data/com.mypackage/databases/";
private static String DB_NAME = "database.sqlite";
private static String TABLE_NAME = "content_table";
private SQLiteDatabase database = null;
private final Context context;
public DatabaseAdapter(Context context){
this.context = context;
}
private void openDatabase() throws SQLiteException{
DatabaseHelper databaseHelper = new DatabaseHelper(context, DB_NAME);
SQLiteDatabase db = null;
if(!checkDatabase()){
try{
//Tried to create db before copying, so file should exist
db = databaseHelper.getReadableDatabase();
db.close();
copyDatabase();
}catch(IOException exception){
Log.d("DatabaseAdapter", "Error copying DB: "+exception);
}
}
database = SQLiteDatabase.openDatabase(DB_PATH+DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
}
private void closeDatabase(){
database.close();
}
public ArrayList<String> queryCategories(){
try{
openDatabase();
}catch(SQLiteException exc){
exc.printStackTrace();
}
//.............................
return result;
}
private boolean checkDatabase(){
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDatabase() throws IOException{
InputStream inputStream = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer))>0){
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
DatabaseHelper 很简单:
ublic class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name){
super(context, name, null, 1);
}
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
什么都试过了!我试过玩扩展!但我仍然得到一个错误:
复制数据库时出错:java.io.FileNotFoundException: /data/data/com.mypackage/databases/database.sqlite (No such file or directory)
我检查了模拟器,我的文件在那里,所以我应该可以写入它! 请,任何帮助!快把我逼疯了!
UPD 我尝试将它放在 SD 卡上,它可以工作。但还是不明白为什么我不能将它写入应用数据文件夹。
【问题讨论】: