1

I am trying to add cordova SQLite database in my ionic project which is scanning qrcode & inserting details into local database.

My database initialization is this:

var db = null;
var app = angular.module('scanstarter', ['ionic', 'ionic-material', 'ngCordova']);

app.run(function ($ionicPlatform, $ionicLoading, $cordovaGeolocation, $cordovaSQLite) {
$ionicPlatform.ready(function () {

    document.addEventListener("deviceready", function () {
        // Sqlite database initialization
        db = $cordovaSQLite.openDB({name: 'scanstarter.db'});
        // create table for product scan
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS productScan (id integer primary key, unique_id text, productName text, serialNo text, manufacturer text, department text, time text, latitude text, longitude text, actionRequired text, sync text)");
        // create table for comments
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS comments (id integer primary key, unique_id text, comment text)");
    }, false);
});

})

My scan function flow is this:

    $scope.goToScan = function () {
    cordova.plugins.barcodeScanner.scan(
            function (result) {
                if (!result.cancelled)
                {
                    if (result.format == "QR_CODE")
                    {
                        var scannedData = result.text;

                        var posOptions = {enableHighAccuracy: true};
                        $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
                            //Get latitude and longitude
                            var latitude = position.coords.latitude;
                            var longitude = position.coords.longitude;
                            //Initial Split with #
                            var splitArray = scannedData.split("#");
                            var UniqueId = splitArray[0];
                            var ProductName = splitArray[1];
                            var SerialNo = splitArray[2];
                            var Manufacturer = splitArray[3];
                            var Department = splitArray[4];
                            //Individual Split with :
                            var UniqueIdArray = UniqueId.split(':');
                            var ProductNameArray = ProductName.split(':');
                            var SerialNoArray = SerialNo.split(':');
                            var ManufacturerArray = Manufacturer.split(':');
                            var DepartmentArray = Department.split(':');

                            if ((UniqueIdArray[0] == 'unique_id') && (ProductNameArray[0] == 'product_name') && (SerialNoArray[0] == 'serial_no') && (ManufacturerArray[0] == 'manufacturer') && (DepartmentArray[0] == 'department')) {
//Insert query part start
                                var query = "INSERT INTO productScan (unique_id, productName, serialNo, manufacturer, department, time, latitude, longitude, actionRequired, sync) VALUES (?,?,?,?,?,?,?,?,?,?)";
                                $cordovaSQLite.execute(db, query, [UniqueIdArray[1], ProductNameArray[1], SerialNoArray[1], ManufacturerArray[1], DepartmentArray[1], Math.floor(Date.now() / 1000), latitude, longitude, 'N', 'N']).then(function (res) {
                                    alert(JSON.stringify(res));

                                }, function (err) {
                                    alert(JSON.stringify(err));
                                });
//Insert query part end
                                $state.go('app.scan');

                            } else {
                                alert('Invalid QR-Code. This QR-Code is not part of Inventory!.');
                            }

                        }, function (err) {
                            $ionicLoading.show({template: 'Kindly check your mobile GPS. GPS must be on!.'});
                            $timeout(function () { // server replies when username or password is incorrect
                                $ionicLoading.hide();
                            }, 3000)
                        });

                    }
                }
            },
            function (error) {
                alert("Scanning failed: " + error);
            }
    );
}

what happens is when i comment the insert query part of cordovaSQLite and build the app and check it then it successfully scan and then navigates to next page. But when i uncomment it and build the apk and run it on my mobile it does not navigate me to next page. I saw the flow working by adding subsequent alerts after each modile of execution and then i found that i am getting stuck at the point where sqlite insert query code starts.

What is the error occuring here i am really not getting. Is there something i am missing?

Thanks in advance for quick response.

UPDATE

Basic example is here The controller code is this

    $scope.insert = function (firstname, lastname) {
    alert('HI'+firstname+' '+lastname);
    var query = "INSERT INTO people (firstname, lastname) VALUES (?,?)";
    $cordovaSQLite.execute(db, query, [firstname, lastname]).then(function (res) {
        alert('HI2');
        alert("INSERT ID -> " + res.insertId);
    }, function (err) {
        alert(err);
    });
}

$scope.select = function (lastname) {
    alert('HI'+lastname);
    var query = "SELECT firstname, lastname FROM people WHERE lastname = ?";
    $cordovaSQLite.execute(db, query, [lastname]).then(function (res) {
        alert('HI');
        if (res.rows.length > 0) {
            alert("SELECTED -> " + res.rows.item(0).firstname + " " + res.rows.item(0).lastname);
        } else {
            alert("No results found");
        }
    }, function (err) {
        alert(err);
    });
}

View looks like this:

    <button class="button button-block button-small button-energized" ng-click="insert('sagar', 'barawade')">INSERT</button>
    <button class="button button-block button-small button-energized" ng-click="select('barawade')">SELECT</button>

Initialization is same as given above.

On this code even i am not able to get the alerts for inserted id & also nothing for select query as response.

10
  • What error message gets returned? Commented Mar 31, 2016 at 11:57
  • actually nothing is getting returned. it directly stop their and does not navigate me to next view. Commented Mar 31, 2016 at 12:43
  • if i comment the Insert query part and run it then it navigates me to app.scan view Commented Mar 31, 2016 at 12:47
  • 1
    wrap it in a JavaScript try catch and see if anything gets caught?... try { //insert sqlite code... } catch (err) { alert(err.message); } Commented Mar 31, 2016 at 13:18
  • 1
    Sounds like your db variable is null so when you try to do a transaction it wont work. Try doing the same JavaScript try catch statement around your db initialisation because there might be an error when you open it... db = $cordovaSQLite.openDB({name: 'scanstarter.db'}); Commented Apr 4, 2016 at 8:13

2 Answers 2

2

I got it finally after a weeks long efforts.

I need to specify the database like the following way

db = $cordovaSQLite.openDB({name: "biziscan.db", location: 1, iosDatabaseLocation: 'default'});

Need to specify the default location for database. It is their in the github file of plugin but has not got updated in the ngCordova site.

Sign up to request clarification or add additional context in comments.

Comments

1

while creating table, for time column you have given text as datatype. But while inserting u are inserting a integer. Please check that

7 Comments

thanks for your response but even i turned for trying a basic example where i created the same db and just tried adding sample data as shown in this link thepolyglotdeveloper.com/2014/11/… still it doesn't work.
i have added the basic example too. u can check the update part
is that going into success block or not...? or you are getting any error? can u post your log data?
Neither success block executes nor the error block. Just a screen is displayed as the alert i have set to verify whether the function is calling or not.
is there any version issue??.. My android version was 4.0.2 which i am updating now while my ionic CLI verison is 1.7.14.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.