Qt Android assets



  • Hey guys,

    I got the following problem:
    I'm developing a cross platform application (Linux/Android) and I'm stuck at deploying my SQLite database to Android - it works perfectly well for Linux.
    I managed to add my db file to assets through the following code in my .pro file

    deployment.files += rako.db
    deployment.path = /assets
    INSTALLS += deployment

    Now in my DbManager C++ file where I handle my Database Connections I'm not able to get the SQLite database running :(
    [...]
    db_.setDatabaseName("assets:/rako.db");

    After reading some of the posts at stackoverflow I'm still not able to get this accomplished.
    Do I miss something?

    Thanks guys,

    Max



  • @KMax

    1. To access Android assets from C++ you need AAssetManager API.
    2. Since you're working with this file from C++, it's easier to bundle it as a Qt resource. Of course, if it's very large that may not be a good idea.
    3. If your database is NOT read-only, AFAIK you won't be able to modify its asset in-place. Copy it to your /data folder when initializing the app and then work with it there.


  • Hi Violet Giraffe,

    thank you for your reply.
    I tried to load the database as a qrc - resouce, but nonetheless it doesn't work.

    db_.setDatabaseName("qrc:/database/rako.db");

    But it just returns me the following error:
    connection failed "out of memory Error opening database"

    What are the steps I'll have to do?

    • add it to the qrc items

    • load it with the setDatabaseName() ?

    • afterwards copy it?

    Tank you



  • For everyone else who is have the same problem, this did the trick:

    .pro file:

    android {
        data.files = db/flags.sqlite
        data.path = /assets/db
        INSTALLS += data
    }
    

    .cpp file

      QFile dfile("assets:/db/flags.sqlite");
       QString filePath = QStandardPaths::writableLocation( QStandardPaths::StandardLocation::AppLocalDataLocation );
       filePath.append( "/flags.sqlite");
       if (dfile.exists()) {
           if( QFile::exists( filePath ) )
               QFile::remove( filePath );
    
           if( dfile.copy( filePath ) )
               QFile::setPermissions( filePath, QFile::WriteOwner | QFile::ReadOwner );
    
       }
       d->database.setDatabaseName( filePath );
    #else
       d->database.setDatabaseName( "db/flags.sqlite" );
    #endif
    
       if( d->database.open() ) {
           qDebug( "DB open successful ");
    
           QSqlQuery q(d->database);
           q.exec("SELECT * from flags");
           q.last();
           d->dbSize = q.at() + 1;
       }
       else {
           qDebug( "DB failed" );
       }
    }
    

    Link: Click me


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.