我想從資產文件夾複製SQLite數據庫。這是我的DatabaseAdapter.java類從資產文件夾複製SQLite數據庫
package com.example.dictionary;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseAdapter extends SQLiteOpenHelper {
static String DB_PATH = "/data/data/com.example.dictionary/databases/";
static String DB_NAME = "dict.db";
SQLiteDatabase db;
private final Context mContext;
public DatabaseAdapter(Context context) {
super(context, DB_NAME, null, 1);
this.mContext = context;
}
public void createDB(){
boolean dbExist = checkDB();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDB();
} catch (Exception e) {
throw new Error("Error copying DB");
}
}
}
private void copyDB() throws IOException {
InputStream dbInput = mContext.getAssets().open(DB_NAME);
String outFile = DB_PATH + DB_NAME;
OutputStream dbOutput = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
int length;
while ((length = dbInput.read(buffer))>0) {
dbOutput.write(buffer,0,length);
}
dbOutput.flush();
dbOutput.close();
dbInput.close();
}
private boolean checkDB() {
SQLiteDatabase check = null;
try {
String dbPath = DB_PATH+DB_NAME;
check = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (Exception e) {
// TODO: handle exception
}
if (check!=null) {
check.close();
}
return check != null ? true : false;
}
public void openDB(){
String dbPath = DB_PATH+DB_NAME;
db = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void close(){
if(db != null)
db.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
當我運行程序的時候,是不是錯誤。但是當我檢查數據庫文件夾我看到文件「dict.db」但只有12.00K,並且只有android_metadata表。請幫幫我。謝謝。
請使用'SQLiteAssetHelper'此:https://github.com/jgilfelt/android-sqlite-asset-幫手 – CommonsWare 2013-05-03 09:50:14