我正在使用此代码
public class PeopleDBHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = "Person";
public static final String DB_PATH = "/data/data/com.machinarius.labs.preloadedsql/databases/";
public static final String DB_NAME = "preload-test.sqlite";
private static final String DB_PREFS = "whyDoIHaveToDoThisAgain?";
private Context parent;
public PeopleDBHelper(Context context) {
super(context, DB_NAME, null, 1);
parent = context;
SharedPreferences prefs = context.getSharedPreferences(DB_PREFS, 0);
if(prefs.getBoolean("firstRun", true)) {
prefs.edit().putBoolean("firstRun", false).commit();
onCreate(null);
}
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
Log.i(getClass().getSimpleName(), "onCreate()");
InputStream source;
OutputStream destination;
byte[] buffer;
try {
source = parent.getAssets().open(DB_NAME);
destination = new BufferedOutputStream(new FileOutputStream(DB_PATH + DB_NAME));
buffer = new byte[512];
while(source.read(buffer) > 0) {
destination.write(buffer);
}
source.close();
destination.flush();
destination.close();
} catch(IOException ex) {
Log.e(getClass().getSimpleName(), "IOException", ex);
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
}
}
我一直在想......为什么我必须使用 SharedPreferences 来实现那个愚蠢的 hack 才能让 onCreate 触发?即使从设置菜单中擦除应用程序数据并调用 getWritableDatabase() onCreate 也不会触发,从而导致来自持久层的崩溃。我做错了什么?