Coder Social home page Coder Social logo

Comments (10)

shastik avatar shastik commented on May 16, 2024 5

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.

jeffswitzer avatar jeffswitzer commented on May 16, 2024

@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.

jeffswitzer avatar jeffswitzer commented on May 16, 2024

@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.

NathanaelA avatar NathanaelA commented on May 16, 2024

@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.

kazemihabib avatar kazemihabib commented on May 16, 2024

@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.

NathanaelA avatar NathanaelA commented on May 16, 2024

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.

thiagoufg avatar thiagoufg commented on May 16, 2024

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.

jeffswitzer avatar jeffswitzer commented on May 16, 2024

@kazemihabib @shastik thanks much... finally just got back to this and the above code helped me to get it working.

from nativescript-sqlite.

webmeemba avatar webmeemba commented on May 16, 2024

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.

heese avatar heese commented on May 16, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.