Comments (10)
Hi everyone,
I tried @kazemihabib solution and it works.
I have a custom db service (db.service.ts) (did not overloaded nativescript-sqlite library).
I use Angular2
I have to use Android DownloadManager to download DB file. http.getFile
is not ready to download large files.
Here is my code: (maybe it will help to someone)
let dm = new DownloadManager();
dm.downloadFile("https://database_to_download/database_name.db", function(result,uri) {
if (result) {
uri = uri.replace('file://','');
self.copyDatabaseAndroid(databaseName, uri, self.getDatabaseName());
self.initialize(self.getDatabaseName(), true);
}
resolve(true);
dm.unregisterBroadcast();
})
/**
* gets the current application context
* @returns {*}
* @private
*/
_getContext() {
if (app.android.context) {
return (app.android.context);
}
var ctx = java.lang.Class.forName("android.app.AppGlobals").getMethod("getInitialApplication", null).invoke(null, null);
if (ctx) return ctx;
ctx = java.lang.Class.forName("android.app.ActivityThread").getMethod("currentApplication", null).invoke(null, null);
return ctx;
}
copyDatabaseAndroid(name, currentDBPath, oldName) {
if (name.indexOf('/')) {
name = name.substring(name.indexOf('/')+1);
}
//noinspection JSUnresolvedFunction
var dbname = this._getContext().getDatabasePath(name).getAbsolutePath();
var path = dbname.substr(0, dbname.lastIndexOf('/') + 1);
if (oldName != 'church_service.db') {
var olddbname = this._getContext().getDatabasePath(oldName).getAbsolutePath();
var oldpath = olddbname.substr(0, olddbname.lastIndexOf('/') + 1);
try {
var javaFile = new java.io.File(oldpath);
if (javaFile.exists()) {
javaFile.delete();
console.log('Delete old db file success');
} else {
console.log('Old db file not found', oldpath);
}
} catch (err) {
console.info('Delete old db error', err);
}
}
// Create "databases" folder if it is missing. This causes issues on Emulators if it is missing
// So we create it if it is missing
try {
var javaFile = new java.io.File(path);
if (!javaFile.exists()) {
//noinspection JSUnresolvedFunction
javaFile.mkdirs();
//noinspection JSUnresolvedFunction
javaFile.setReadable(true);
//noinspection JSUnresolvedFunction
javaFile.setWritable(true);
}
}
catch (err) {
console.info("SQLITE - COPYDATABASE - Creating DB Folder Error", err);
}
var backupDBPath = path + '/' + name;
var currentDB = new java.io.File(currentDBPath);
var backupDB = new java.io.File(backupDBPath);
var success = false;
try {
var source = new java.io.FileInputStream(currentDB).getChannel();
var destination = new java.io.FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
console.log('DB exported');
success = true;
//Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
} catch(err) {
console.info('Copy DB error', err);
}
return success;
}
public initialize(databaseName: string = '', reInitialize: boolean = false) {
return new Promise((resolve, reject) => {
if (!this.isInitialized || reInitialize) {
console.log('initializeDB');
if (!databaseName) {
databaseName = this.getDatabaseName();
}
this.setDatabaseName(databaseName);
if (!Sqlite.exists(databaseName)) {
Sqlite.copyDatabase(databaseName);
}
(new Sqlite(databaseName))
.then(db => {
console.log('open database: ', databaseName);
this.database = db;
this.isInitialized = true;
this.database.resultType(Sqlite.RESULTSASOBJECT);
this.queryBuilderService.setDatabase(this.database);
resolve(true);
}, error => {
console.log("OPEN DB ERROR", error);
})
.then(db => {
});
} else {
resolve(true);
}
});
}
from nativescript-sqlite.
@kazemihabib I also ran into this problem (on android) of trying to download a database from a remote server and then call copyDatabase on the downloaded file but even though the file has been downloaded to the apps directory copyDatabase doesn't find it. I posted my code snippit in this github issue. couple questions: are the assets folder and app folder 2 different locations? How did you get around this by copying manually? If I instead embed the sqlite file in the apps folder before building the app then the copyDatabase call works.
from nativescript-sqlite.
@NathanaelA is the path that copyDatabase() tries to copy from the same as fs.knownFolders.currentApp().path? On my system that resolves to /data/data/org.nativescript.myappname/files/app
from nativescript-sqlite.
@jeffswitzer - Yes. The copy from path is the root of the app which is that path.
The copyDatabase is really just designed to be a very simple helper for those who include the database as part of the built in app; so that it can be installed in the place that it needs to be. It is not a general purpose routine. :-)
from nativescript-sqlite.
@jeffswitzer I didn't implement it yet , but I know it's possible for example:http://stackoverflow.com/questions/22531789/copy-database-from-sdcard-to-data-data-packagename-databases-folder
from nativescript-sqlite.
I am willing to accept a pull request that implements this functionality; or you can contract with me or another contractor to add this feature.
from nativescript-sqlite.
I'd also like to have it copied from the SD card, or even accessed from there, without needing to copy it to the folder /data/data/org.nativescript.myappname/files/app
from nativescript-sqlite.
@kazemihabib @shastik thanks much... finally just got back to this and the above code helped me to get it working.
from nativescript-sqlite.
Hi, I need help with copyDatabaseAndroid(name, currentDBPath, oldName).
(angular)Me code is the next:
component.ts
var filePath = fs.path.join(fs.knownFolders.currentApp().path, "init2.db");
http.getFile("http://meemba-webs.com.ar/beeorder/init2.db", filePath).then(downloadedFile => {
this.service.setDB(dbName, filePath)
})
service.ts
public setDB(name, path) : void{
console.log('name:'); console.log(name);
if (!sqlite.exists(name)) {
this.copyDatabaseAndroid(name, path, name);
};
new sqlite(name, function(err, db) {
if (!err) {
this.database = db;
}
});
}
private copyDatabaseAndroid(name, currentDBPath, oldName) {
if (name.indexOf('/')) {
name = name.substring(name.indexOf('/')+1);
}
//noinspection JSUnresolvedFunction
var dbname = this._getContext().getDatabasePath(name).getAbsolutePath();
var path = dbname.substr(0, dbname.lastIndexOf('/') + 1);
if (oldName != 'church_service.db') {
var olddbname = this._getContext().getDatabasePath(oldName).getAbsolutePath();
var oldpath = olddbname.substr(0, olddbname.lastIndexOf('/') + 1);
try {
var javaFile = new java.io.File(oldpath);
if (javaFile.exists()) {
javaFile.delete();
console.log('Delete old db file success');
} else {
console.log('Old db file not found', oldpath);
}
} catch (err) {
console.info('Delete old db error', err);
}
}
// Create "databases" folder if it is missing. This causes issues on Emulators if it is missing
// So we create it if it is missing
try {
var javaFile = new java.io.File(path);
if (!javaFile.exists()) {
//noinspection JSUnresolvedFunction
javaFile.mkdirs();
//noinspection JSUnresolvedFunction
javaFile.setReadable(true);
//noinspection JSUnresolvedFunction
javaFile.setWritable(true);
}
}
catch (err) {
console.info("SQLITE - COPYDATABASE - Creating DB Folder Error", err);
}
var backupDBPath = path + '/' + name;
var currentDB = new java.io.File(currentDBPath);
var backupDB = new java.io.File(backupDBPath);
var success = false;
try {
var source = new java.io.FileInputStream(currentDB).getChannel();
var destination = new java.io.FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
console.log('DB exported');
success = true;
//Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
} catch(err) {
console.info('Copy DB error', err);
}
return success;
}
from nativescript-sqlite.
I read this thread first but could not easily extract the key source code. I found another post showing very concise source code (also notice the comment later about checking for the existence of the folder). Maybe, this will help other people facing this issue.
https://discourse.nativescript.org/t/downloading-and-using-an-sqlite-db-file-where-does-it-go/6567/4
from nativescript-sqlite.
Related Issues (20)
- Run ATTACH command? HOT 1
- demo doest work on iOS HOT 2
- In-Memory Databases do not work in android
- Multiple documentation issues (and one real) HOT 4
- execSql weird error handling HOT 1
- Build fails with NativeScript 6.5 ./gradlew (failed with exit code 1) HOT 3
- Point to custom Sqlite3 for paid extension support HOT 6
- Module not found: Error: Can't resolve 'nativescript-sqlite-sync' with commercial licence HOT 2
- Upgrade to Nativescript 7 HOT 2
- Where does actual data store? HOT 1
- Return and display blob into img example? HOT 3
- Execsql failed to prepare:1 HOT 2
- Commercial License HOT 4
- What needs to be modified when working with nativescript 8 ? HOT 3
- Got resultSet of 'undefined' after upgrading to NS 8 HOT 4
- App crashs on IOS 14.5.1 + HOT 7
- Can't resolve 'nativescript-sqlite-commercial/commercial-multi' HOT 9
- iOS: Update from {N} 8.0 to 8.1 creates toString from null error HOT 29
- SELECT error: SQLITE.ALL - Prepare Error 1 when migrating from {N} 6.8 to 8.1 HOT 7
- Uncaught TypeError: nativescript_sqlite__WEBPACK_IMPORTED_MODULE_0__.Sqlite is not a constructor
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from nativescript-sqlite.