這是我的版本從「Silvio Donnini」代碼:), 現在您可以輕鬆地更新數據庫。
private static final String DB_PATH = "/data/data/pakagename/databases/";
private static final String DB_NAME = "databaseName";
private static SQLiteDatabase db;
public static void createDatabaseIfNotExists(Context context,int version) throws IOException {
boolean createDb = false;
File dbDir = new File(DB_PATH);
File dbFile = new File(DB_PATH + DB_NAME);
if (!dbDir.exists()) {
dbDir.mkdir();
createDb = true;
}
else if (!dbFile.exists()) {
createDb = true;
}
else {
// Check that we have the latest version of the db
db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
if (db.getVersion() != version) {
dbFile.delete();
createDb = true;
}
}
if (createDb) {
// Open your local db as the input stream
InputStream myInput = context.getResources().openRawResource(R.raw.database);
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(dbFile);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
SQLiteDatabase dbwrite = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
dbwrite.setVersion(version);
dbwrite.close();
if (db != null)
db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
}
}
public static SQLiteDatabase getStaticDb() {
if (db != null)
return db;
return SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
}
你能分享實用課嗎? 因爲我不明白:「不會讓自己如此掛斷」 非常感謝 – user275788 2010-03-06 12:57:22
我已經添加了我的實用程序類的減少版本,只留下代碼的肉在那裏。 (例如,我強烈建議添加Log語句,但這些示例代碼不是必需的)。無論如何,在這個版本的代碼中,您只需在應用程序啓動時調用createDatabaseIfNotExists(),比如在android.app.Application中擴展onCreate()。 – 2010-03-06 16:30:59
另請注意,如果您的文件大小超過1MB,則read()拋出IoException和資產日誌「數據超出UNCOMPRESSED_DATA_MAX」...我通過在資產中命名我的文件.jpg來解決這個問題 - > aapt沒有試圖壓縮它 – Mikpa 2010-11-14 13:23:00