Du har en række problemer, forudsat at du ønsker at erstatte en eksisterende eksisterende database med en anden kopi.
Problemet du står over for er, at da der eksisterer en database, vil kopien ikke fortsætte, dvs. checkDatabase() vil returnere sandt.
Hvis du blot skulle kalde copyDatabase() så ville databasen blive kopieret hver gang appen køres, hvilket ville være ineffektivt og ødelæggende, hvis databasen kan ændres af brugeren.
Det, du skal gøre, er at have en indikator, som kan testes, for at se, om den allerede eksisterende database er blevet ændret. Der er forskellige måder, men den mest sandsynlige/almindelige måde ville være at bruge SQLite user_version . Dette er en heltalsværdi og bruges ofte til at opdatere den aktuelle database via onUpgrade metode.
Som en del af åbningen af databasen sammenligner SQLiteOpenHelper (og derfor en underklasse deraf) den user_version, der er gemt i databasen, med det angivne versionsnummer (4. parameter til SQLiteOpenHelper-superkaldet), og hvis sidstnævnte er større end værdien, der er gemt i database, så kaldes onUpgrade-metoden. (hvis omvendt, så onDowngrade metode vil blive kaldt, og uden at den er kodet opstår der en undtagelse).
User_versionen kan indstilles i SQLite-styringsværktøjet bruger SQL PRAGMA user_version = n
.
Et andet problem er, at fra Android 9 åbnes databasen som standard i WAL-tilstand (Write-Ahead Logging). Ovenstående kode ved at bruge this.getReadableDatabase();
resulterer i, at -shm- og -wal-filerne bliver oprettet. Deres eksistens resulterer i en fanget fejl (da de så ikke matcher den kopierede database), som derefter resulterer i, at SQLiteOpenHelper opretter en tom (teoretisk brugbar database), som stort set sletter den kopierede database (Jeg tror, det er, hvad der sker ).
Grunden til, at this.getReadableDatabase();
er blevet brugt, er, at det kommer rundt om problemet, at når der ikke er nogen appdata, vil databaserne mappe/mappe eksisterer ikke, og ved at bruge ovenstående oprettes den. Den korrekte måde er at oprette databasens bibliotek/mappe, hvis den ikke eksisterer. Som sådan oprettes -wal- og -shm-filerne ikke.
Det følgende er et eksempel på DabseHelper, der overvinder problemerne og desuden tillader, at ændrede versioner af den eksisterende database kopieres baseret på ændring af user_version.
public class DBHelperV001 extends SQLiteOpenHelper {
public static final String DBNAME = "test.db"; //<<<<<<<<<< obviously change accordingly
//
private static int db_user_version, asset_user_version, user_version_offset = 60, user_version_length = 4;
private static String stck_trc_msg = " (see stack-trace above)";
private static String sqlite_ext_journal = "-journal";
private static String sqlite_ext_shm = "-shm";
private static String sqlite_ext_wal = "-wal";
private static int copy_buffer_size = 1024 * 8; //Copy data in 8k chucks, change if wanted.
SQLiteDatabase mDB;
/**
* Instantiate the DBHelper, copying the databse from the asset folder if no DB exists
* or if the user_version is greater than the user_version of the current database.
* NOTE The pre-existing database copied into the assets folder MUST have the user version set
* to 1 or greater. If the user_version in the assets folder is increased above the
*
* @param context
*/
public DBHelperV001(Context context) {
// Note get the version according to the asset file
// avoid having to maintain the version number passed
super(context, DBNAME, null, setUserVersionFromAsset(context,DBNAME));
if (!ifDbExists(context,DBNAME)) {
copyDBFromAssets(context, DBNAME,DBNAME);
} else {
setUserVersionFromAsset(context,DBNAME);
setUserVersionFromDB(context,DBNAME);
if (asset_user_version > db_user_version) {
copyDBFromAssets(context,DBNAME,DBNAME);
}
}
// Force open (and hence copy attempt) when constructing helper
mDB = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/**
* Check to see if the databse file exists
* @param context The Context
* @param dbname The databse name
* @return true id database file exists, else false
*/
private static boolean ifDbExists(Context context, String dbname) {
File db = context.getDatabasePath(dbname);
if (db.exists()) return true;
if (!db.getParentFile().exists()) {
db.getParentFile().mkdirs();
}
return false;
}
/**
* set the db_user_version according to the user_version obtained from the current database file
* @param context The Context
* @param dbname The database (file) name
* @return The user_version
*/
private static int setUserVersionFromDB(Context context, String dbname) {
File db = context.getDatabasePath(dbname);
InputStream is;
try {
is = new FileInputStream(db);
} catch (IOException e) {
throw new RuntimeException("IOError Opening " + db.getPath() + " as an InputStream" + stck_trc_msg);
}
db_user_version = getUserVersion(is);
Log.d("DATABASEUSERVERSION","Obtained user_version from current DB, it is " + String.valueOf(db_user_version)); //TODO remove for live App
return db_user_version;
}
/**
* set the asset_user_version according to the user_version from the asset file
* @param context
* @param assetname
* @return
*/
private static int setUserVersionFromAsset(Context context, String assetname) {
InputStream is;
try {
is = context.getAssets().open(assetname);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IOError Getting asset " + assetname + " as an InputStream" + stck_trc_msg);
}
asset_user_version = getUserVersion(is);
Log.d("ASSETUSERVERSION","Obtained user_version from asset, it is " + String.valueOf(asset_user_version)); //TODO remove for Live App
return asset_user_version;
}
/**
* Retrieve SQLite user_version from the provied InputStream
* @param is The InputStream
* @return the user_version
*/
private static int getUserVersion(InputStream is) {
String ioerrmsg = "Reading DB header bytes(60-63) ";
int rv;
byte[] buffer = new byte[user_version_length];
byte[] header = new byte[64];
try {
is.skip(user_version_offset);
is.read(buffer,0,user_version_length);
ByteBuffer bb = ByteBuffer.wrap(buffer);
rv = ByteBuffer.wrap(buffer).getInt();
ioerrmsg = "Closing DB ";
is.close();
return rv;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IOError " + ioerrmsg + stck_trc_msg);
}
}
/**
* Copy the database file from the assets
* Note backup of existing files may not be required
* @param context The Context
* @param dbname The database (file)name
* @param assetname The asset name (may therefore be different but )
*/
private static void copyDBFromAssets(Context context, String dbname, String assetname) {
String tag = "COPYDBFROMASSETS";
Log.d(tag,"Copying Database from assets folder");
String backup_base = "bkp_" + String.valueOf(System.currentTimeMillis());
String ioerrmsg = "Opening Asset " + assetname;
// Prepare Files that could be used
File db = context.getDatabasePath(dbname);
File dbjrn = new File(db.getPath() + sqlite_ext_journal);
File dbwal = new File(db.getPath() + sqlite_ext_wal);
File dbshm = new File(db.getPath() + sqlite_ext_shm);
File dbbkp = new File(db.getPath() + backup_base);
File dbjrnbkp = new File(db.getPath() + backup_base);
File dbwalbkp = new File(db.getPath() + backup_base);
File dbshmbkp = new File(db.getPath() + backup_base);
byte[] buffer = new byte[copy_buffer_size];
int bytes_read = 0;
int total_bytes_read = 0;
int total_bytes_written = 0;
// Backup existing sqlite files
if (db.exists()) {
db.renameTo(dbbkp);
dbjrn.renameTo(dbjrnbkp);
dbwal.renameTo(dbwalbkp);
dbshm.renameTo(dbshmbkp);
}
// ALWAYS delete the additional sqlite log files
dbjrn.delete();
dbwal.delete();
dbshm.delete();
//Attempt the copy
try {
ioerrmsg = "Open InputStream for Asset " + assetname;
InputStream is = context.getAssets().open(assetname);
ioerrmsg = "Open OutputStream for Databse " + db.getPath();
OutputStream os = new FileOutputStream(db);
ioerrmsg = "Read/Write Data";
while((bytes_read = is.read(buffer)) > 0) {
total_bytes_read = total_bytes_read + bytes_read;
os.write(buffer,0,bytes_read);
total_bytes_written = total_bytes_written + bytes_read;
}
ioerrmsg = "Flush Written data";
os.flush();
ioerrmsg = "Close DB OutputStream";
os.close();
ioerrmsg = "Close Asset InputStream";
is.close();
Log.d(tag,"Databsse copied from the assets folder. " + String.valueOf(total_bytes_written) + " bytes were copied.");
// Delete the backups
dbbkp.delete();
dbjrnbkp.delete();
dbwalbkp.delete();
dbshmbkp.delete();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IOError attempting to " + ioerrmsg + stck_trc_msg);
}
}
}
Eksempel på brug
Overvej følgende aktivfiler (sqlite-databaser) (advarsel, da de er, ville appen mislykkes ) :-
Så der er to databaser (identisk bar user_version som indstillet ved hjælp af PRAGMA user_version = 1
og PRAGMA user_version = 2
hhv er omdøbt til test.db og følgende aktivitet bruges :-
public class MainActivity extends AppCompatActivity {
DBHelperV001 mDbhlpr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDbhlpr = new DBHelperV001(this);
DatabaseUtils.dumpCursor(
mDbhlpr.getWritableDatabase().query(
"sqlite_master",
null,null,null,null,null,null
)
);
}
}
- Dette instansierer simpelthen databasehjælperen (som kopierer eller bruger databasen) og dumper derefter sqlite_master-tabellen.
Loggen indeholder :-
04-02 12:55:36.258 644-644/aaa.so55441840 D/ASSETUSERVERSION: Obtained user_version from asset, it is 1
04-02 12:55:36.258 644-644/aaa.so55441840 D/COPYDBFROMASSETS: Copying Database from assets folder
04-02 12:55:36.262 644-644/aaa.so55441840 D/COPYDBFROMASSETS: Databsse copied from the assets folder. 69632 bytes were copied.
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out: >>>>> Dumping cursor [email protected]
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out: 0 {
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out: type=table
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out: name=android_metadata
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out: tbl_name=android_metadata
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out: rootpage=3
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out: sql=CREATE TABLE android_metadata (locale TEXT)
04-02 12:55:36.266 644-644/aaa.so55441840 I/System.out: }
04-02 12:55:36.266 644-644/aaa.so55441840 I/System.out: 1 {
04-02 12:55:36.266 644-644/aaa.so55441840 I/System.out: type=table
04-02 12:55:36.266 644-644/aaa.so55441840 I/System.out: name=shops
..........
Når den nye version af DB introduceres, som har en user_version på 2
- dvs. test.db som var test.dbV1 er omdøbt til test.dbV1 OG så
- (sletter det effektivt)
- test.dbV2 omdøbes derefter til test.db
- (ved at introducere den nye aktivfil) så :-
Og appen køres så igen, så indeholder loggen :-
04-02 13:04:25.044 758-758/? D/ASSETUSERVERSION: Obtained user_version from asset, it is 2
04-02 13:04:25.046 758-758/? D/ASSETUSERVERSION: Obtained user_version from asset, it is 2
04-02 13:04:25.046 758-758/? D/DATABASEUSERVERSION: Obtained user_version from current DB, it is 1
04-02 13:04:25.047 758-758/? D/COPYDBFROMASSETS: Copying Database from assets folder
04-02 13:04:25.048 758-758/? D/COPYDBFROMASSETS: Databsse copied from the assets folder. 69632 bytes were copied.
04-02 13:04:25.051 758-758/? I/System.out: >>>>> Dumping cursor [email protected]
04-02 13:04:25.052 758-758/? I/System.out: 0 {
04-02 13:04:25.052 758-758/? I/System.out: type=table
04-02 13:04:25.052 758-758/? I/System.out: name=android_metadata
04-02 13:04:25.052 758-758/? I/System.out: tbl_name=android_metadata
04-02 13:04:25.052 758-758/? I/System.out: rootpage=3
04-02 13:04:25.052 758-758/? I/System.out: sql=CREATE TABLE android_metadata (locale TEXT)
04-02 13:04:25.052 758-758/? I/System.out: }
04-02 13:04:25.052 758-758/? I/System.out: 1 {
04-02 13:04:25.052 758-758/? I/System.out: type=table
04-02 13:04:25.052 758-758/? I/System.out: name=shops
Til sidst, med en efterfølgende kørsel, dvs. ingen opdateret aktiv, viser loggen:-
04-02 13:05:50.197 840-840/aaa.so55441840 D/ASSETUSERVERSION: Obtained user_version from asset, it is 2
04-02 13:05:50.198 840-840/aaa.so55441840 D/ASSETUSERVERSION: Obtained user_version from asset, it is 2
04-02 13:05:50.198 840-840/aaa.so55441840 D/DATABASEUSERVERSION: Obtained user_version from current DB, it is 2
04-02 13:05:50.201 840-840/aaa.so55441840 I/System.out: >>>>> Dumping cursor [email protected]
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: 0 {
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: type=table
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: name=android_metadata
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: tbl_name=android_metadata
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: rootpage=3
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: sql=CREATE TABLE android_metadata (locale TEXT)
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: }
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: 1 {
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: type=table
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: name=shops
dvs. ingen kopi udført, da aktivet reelt er det samme