我在尝试让SQLite使用Android时遇到严重问题。我不断收到错误,例如“未知错误(代码14):无法打开数据库”。
我发现暂时消除此错误的一种方法是删除数据库然后创建一个。甚至可能没有数据库,但调用deleteDatabase()似乎可以解决问题。
File DB_PATH = getApplicationContext().getDatabasePath("test.db");
DB_PATH.mkdirs();
DatabaseHelper dbh = DatabaseHelper.getHelper(this);
SQLiteDatabase db;
SQLiteDatabase.deleteDatabase(DB_PATH);
db = dbh.getWritableDatabase();
DatabaseHelper
public DatabaseHelper(Context ctx) {
super(ctx, ctx.getApplicationContext().getDatabasePath("test.db").getPath(), null, 10);
this.context = ctx;
}
public static synchronized DatabaseHelper getHelper(Context context) {
if (instance == null) {
instance = new DatabaseHelper(context);
}
return instance;
}
我想知道为什么删除数据库会有所不同,一般的建议会受到赞赏?
答案 0 :(得分:0)
尝试使用此模板
public class MyDBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myDatabase.db";
private static final int SCHEMA = 1;
private static volatile MyDBHelper sInstance;
private MyDBHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA);
}
public static MyDBHelper getInstance(Context context) {
if (sInstance == null) {
synchronized (MyDBHelper.class) {
if (sInstance == null) {
sInstance = new MyDBHelper(context.getApplicationContext());
}
}
}
return sInstance;
}
@Override
public void onCreate(SQLiteDatabase db) {
// create your tables here
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// handle db upgrade or leave blank
}
}