$cordovaSQLite issue


#1

Hi,
im using $cordovaSQLite in my project
when user click archive button in one post , that is archived in my db and i can put those posts in an array and show it with ng-repeat
my problem is : when i test it in browser it work fine but when i test it in android device the array is empty !!
the rows of my table is created and i can see res.rows.length in alert but my array in alert look like this: [,]
what should i do ??
thank you.


#2

Are you using the same code to create/open the database for both browser and android? How are you populating your db?


#3

@juliosampaio
I used this code :
https://gist.github.com/borissondagh/29d1ed19d0df6051c56f
@mhartington


#4

Hey, @mohamadreza_gs! Would be easier to help you if you post your actual code, because this is just the example that you used to implement yours. I guess the issue is not in above code.


#5

@juliosampaio thanks for your response

app.js:

var newsFeedModule = angular.module('starter', 
                    [
                        'ionic',
                        'ngCordova',
                        'ngStorage',
                        'mgs_Services',
                        'ionic-material',
                        'ionMdInput',
                        'starter.directives',
                        'starter.filters'
                    ]);
newsFeedModule.run(function($ionicPlatform, $cordovaSQLite) {
  $ionicPlatform.ready(function() {

   if(window.cordova && window.cordova.plugins.Keyboard) {
       cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
   }
   if(window.StatusBar) {
      StatusBar.styleDefault();
   }

// -------- Data Base -----------
if(window.cordova) {
  // App syntax
  db = $cordovaSQLite.openDB("myapp.db");
} else {
  // Ionic serve syntax
  db = window.openDatabase("myapp.db", "1.0", "My app", -1);
}

$cordovaSQLite
     .execute(db, "CREATE TABLE IF NOT EXISTS favorite ( id integer, questionId integer primary key, categoryId integer, categoryName text, title text, content text, date text, image text, brief text, explain text )"); });});

my services:

mgs_Services.factory('mgs_dataBase',
["$cordovaSQLite", "$timeout", "$q", "$ionicPlatform", "$rootScope",
function($cordovaSQLite, $timeout, $q, $ionicPlatform, $rootScope){
	var dbService = this;
	var listID = [];



		  // Handle query's and potential errors
		  dbService.query = function (query, parameters) {
		    parameters = parameters || [];
		    var q = $q.defer();

		    $ionicPlatform.ready(function () {
		      $cordovaSQLite.execute(db, query, parameters)
		        .then(function (result) {
		          q.resolve(result);
		        }, function (error) {
		          console.warn('I found an error');
		          console.warn(error);
		          q.reject(error);
		        });
		    });
		    return q.promise;
		  }






	dbService.addOrDeleteFavorite = function( questionObj ){
			var questionId = questionObj.id,
				categoryId = questionObj.categoryId,
				categoryName = questionObj.categoryName,
				title = questionObj.title,
				content = questionObj.content,
				date = questionObj.date,
				image = questionObj.image,
				brief = questionObj.brief,
				explain = questionObj.explain;

	        var query = "INSERT INTO favorite ( questionId, categoryId, categoryName, title, content, date, image, brief, explain) VALUES (?,?,?,?,?,?,?,?,?)";
		    var q = $q.defer();
		    $ionicPlatform.ready(function () {
		      $cordovaSQLite.execute(db, query, [ questionId, categoryId, categoryName, title, content, date, image, brief, explain])
		        .then(function (result) {
		          q.resolve(result);
		        }, function (error) {
		          dbService.removeFromDB(questionId);
		          // console.warn('I found an error');
		          // console.warn(error);
		          q.reject(error);
		        });
		    });
		    return q.promise;
	};







	dbService.removeFromDB = function(questionId){
		var parameter = [questionId];
        return dbService.query("DELETE FROM favorite WHERE questionId = (?)", parameter)
	}





	dbService.getDatabaseListID = function(){
	    return dbService.query("SELECT * FROM favorite")
			.then(function(res){
				if(res.rows.length > 0) {
			    	for (var i = 0; i < res.rows.length; i++) {
			    		listID.push(res.rows[i].questionId);
			    	};  
			        // console.log("listID in service : ", listID);
			        $timeout(function(){
			        	dbService.listID = listID;
			        },200);
			    } else {
			        console.log("empty");
			    }
			});
	};






	dbService.getAll = function(res) {
		var output = [];

        if(res.rows.length > 0) {
        	for (var i = 0; i < res.rows.length; i++) {
        		output.push(res.rows[i]);
        	};  
        	$rootScope.emptyList = false;              
            // console.log(output)
        } else {
            $rootScope.emptyList = true;
        }

		return output;
	}


	dbService.getDatabaseListFavorite = function(){
	    return dbService.query("SELECT * FROM favorite")
			.then(function(res){
	            return dbService.getAll(res);
			});
	};



	dbService.listID = listID;


	return dbService;

}])

my controller for add to db:

newsFeedModule.controller("homepageController", ["$scope","mgs_dataBase",function( $scope, mgs_dataBase ){
		$scope.likePost = function( item ){
			mgs_dataBase.addOrDeleteFavorite(item);
		};
	}]);

my controller for show a list from db:

newsFeedModule.controller("favoriteController", 
["$scope", "mgs_dataBase", "$rootScope",
function($scope, mgs_dataBase, $rootScope){
	$scope.$on('$stateChangeSuccess',
		function(evt) {
	        mgs_dataBase.getDatabaseListFavorite().then(function(marked){
	       		$scope.marked = marked;
	    	});
    	}
    );
}]);

I said it work very good in chrome but in android in my getAll function:

alert( output);    // [,,,,,]

#6

Hi,

Try replacing the code bellow

With

db = window.sqlitePlugin.openDatabase({name:'myapp.db'});

also, replace all uses of $cordovaSQLite and $cordovaSQLite.execute. Instead, you should use your db variable to perform all the database actions. What I mean is:

change this:

... $cordovaSQLite.execute(db, query, parameters) ...

For this:

... db.executeSql(sql, parameters) ...

Have a look at https://github.com/litehelpers/Cordova-sqlite-storage for more information. Any doubt, just ask.

Good luck!


#7

Hi @juliosampaio finaly i could fix my problem
for push data in my arrays i used :

output.push(res.rows[i]);

that works in the browser but on device it does not work

now i changed it to :

output.push(res.rows.item(i));

and with this, my problem fixed

Thank you for your attention

Good Luck :wink: