我在此page上关注了本教程。我完全遵循了它,但我仍然无法使预先填充的数据库文件工作。我一直收到错误说.getReadableDatabase或.getWritableDatabase是递归调用的。还尝试了这个page的答案的解决方案,但它也不起作用。有没有更简单的方法将预先填充的数据库复制到本地数据库,这使我能够更新和创建数据?
答案 0 :(得分:0)
试试这个:
public class DatabaseManager {
private DatabaseHelper dataHelper;
private SQLiteDatabase mDb;
private Context ctx;
private String DATABASE_PATH = "/data/data/Your_Package_Name/databases/";
private static String DATABASE_NAME = "Your_Database";
private static String TABLE_NAME = "Your_Table";
private static final int DATABASE_VERSION = 1;
String Class_Tag = "DatabaseManager";
public DatabaseManager(Context ctx) {
this.ctx = ctx;
dataHelper = new DatabaseHelper(ctx);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
@SuppressWarnings("unused")
Context myContext = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.myContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("DBHelper", "Upgrading database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data");
onCreate(db);
}
}
public boolean checkDataBase() {
File f = null;
try {
String myPath = DATABASE_PATH + DATABASE_NAME;
f = new File(myPath);
} catch (Exception e) {
Log.e(Class_Tag, "checkDataBase()", e);
}
return f.exists();
}
public void createDataBase() {
try {
openDB();
InputStream myInput = ctx.getAssets().open(DATABASE_NAME + ".db");
OutputStream myOutput = new FileOutputStream(DATABASE_PATH
+ DATABASE_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
if (mDb.isOpen())
mDb.close();
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
Log.e(Class_Tag, "createDataBase()", e);
}
}
public DatabaseManager openDB() throws SQLException {
mDb = dataHelper.getWritableDatabase();
return this;
}
public void closeDB() {
try {
if (mDb != null) {
mDb.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
并在MainActivity中
DatabaseManager dbMgr=new DatabaseManager(this);
try {
if (!dbMgr.checkDataBase()) {
dbMgr.createDataBase();
}
} catch (Exception e) {
Log.e(Class_Tag, "onCreate()", e);
} finally {
dbMgr.closeDB();
}
希望它有所帮助...