I am developing a Flutter application that uses an SQLite database. The user can download the database from Google Drive usin public shared link. If new version of db is available, automaticaly repalce the existing database. However, I am having trouble when download. this error is occured "
file is encrypted or is not a database
E/DefaultDatabaseErrorHandler( 5315): !@ Corruption reported by sqlite (26) on database: /data/user/0/com.example.replace_db/databases/contacts.db
E/DefaultDatabaseErrorHandler( 5315): !@ dbObj has been closed
I/flutter ( 5315): Database updated to version 2."
Mycode is,
Future<void> checkAndReplaceDatabase() async {
String databaseUrl='https://drive.google.com/file/d/1Qt4xigUU3d7tO-sdyZVZyQKei9l6AvBz';
// Define the expected database version.
final int expectedVersion = 2; // Change this to your desired version.
// Get a reference to the device's database file.
String databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'contacts.db');
// Open the database.
Database database = await openDatabase(path);
// Get the current database version.
int currentVersion = await database.getVersion();
if (currentVersion < expectedVersion) {
// New version is available. Download and replace the database.
// Close the database before replacing it.
await database.close();
// Download the new database from the specified URL.
var response = await http.get(Uri.parse(databaseUrl));
if (response.statusCode == 200) {
// Save the downloaded file to the device's database path.
File newDatabaseFile = File(path);
await newDatabaseFile.writeAsBytes(response.bodyBytes);
// Open the new database.
Database newDatabase = await openDatabase(path);
// Set the new version for the database.
await newDatabase.setVersion(expectedVersion);
// Close the new database.
await newDatabase.close();
print('Database updated to version $expectedVersion.');
} else {
print('Failed to download the new database.');
}
} else {
// The database is up to date.
print('Database is already up to date (version $currentVersion).');
}
}
Please help.
The function works fine. The problem is the url is returning a HTML document, which looks like it's written as bytes to contacts.db.
Try changing the url to directly download from the link like so: Replace
file/d/
withuc?id=
then place&export=download
at the end.This should work for now. But, It depends on the service provider and these links may break, if it's not the recommended way. Seek the docs.