Using Sqlite on Android with Phonegap

Asked

Viewed 466 times

8

Guys, I have a little problem... I’m making an application and I’m using the sqlite on android to save a copy of my database, so far it’s okay, is working, is copying the data the only problem I found is the following.

To make it clearer I’m putting the snippet of my code that "populates" my sqlite database.

var _db;

var DataBase = {

    url : 'http://192.168.1.26:9075/',

    //construtor 
    init: function(){        

        try{
            _db = window.sqlitePlugin.openDatabase(
                {
                    name: "Banco29.db",
                    location: 0 //1
                });
        }catch(e){
            Funcoes.alerta(e,'Erro');
        }

    },

    popularTabela: function(tbl,unidade){
            var nome = tbl.split('.');
            myApp.showPreloader('Atualizando a tabela: '+nome[1]+ ', Isso pode levar alguns minutos, não feche o aplicativo');

            console.log("Populando: "+tbl);
            $.ajax({
                    type: "GET",
                    url: DataBase.url+"procDataBase.php?acao=PopularDados&tabela="+tbl+"&unidade="+unidade,
                    complete:function(){
                     // myApp.hidePreloader();
                    },               
                    success: function (json) {
                        var json = JSON.parse(json);
                        if(json.result == true){
                            var tamanho = json.dados.length;

                           //if(nome[1] === 'ocupacao'){ console.log(JSON.stringify(json)); }

                            for (var i = 0; i < tamanho; i++) {                    
                                if(json.dados[i] !== null && json.dados[i] !== 'null' && typeof(json.dados[i]) !== 'object'){
                                    //console.log(json.dados[i]);
                                    _db.executeSql(json.dados[i], [], function (tx, res){

                                    }, function (t,e){
                                        Funcoes.alerta('Error: '+nome[1]+' '+e.message,'Aviso');
                                    });
                                }
                            }; 
                        }   

                        myApp.hidePreloader();               

                    },error: function(){
                       Funcoes.alerta('Erro para atualizar tabela: '+nome[1]+ ' atualize manualmente a mesma.','Erro');
                       myApp.hidePreloader();  
                    }
            },"json");

        }
}

I make a requisition $.ajax on my server and it returns me an array of Insert, these Insert are the data I am copying from my online database, have table for example that has 5 thousand records, here that enters the problem, at the time that starts a request $.ajax i place a "loading" message displaying for the user and within the "success" function of the $.ajax I put it to enter the query that my request returned and in the end I put to hide the message myApp.hidePreloader();, and here is my problem, at the time the request with the server ends it already hides the Loading message but the application keeps working and inserting the query, logically it should hide the loading message only after it finishes all the processes isn’t it? And my problem is being at this point, because I need the message only "hide" after finishing, as said has a table that has 5 thousand records and until finished inserting the application gets stuck and the person can not move.

I appreciate the help.

  • Take a look at my post http://answall.com/questions/84194/chain-de-requisi%C3%A7%C3%B5es-ass%C3%Adncronas

  • I may be wrong, but I think you’re making your app a little insecure. Even as a mobile app, there’s debugging via Chrome://Inspect and anyone will be able to see the requests being made, so know exactly how your database works and even change data manually. I advise you to save only trivial data and not an entire table to the customer

  • Also what other suggestion do you have to improve security? Thanks for the tip!

1 answer

1

In the callback of the _db.executeSql you can check if the last record has been processed and then hide its loading.

// Uso de função imediata (Immediately Invoked Function)
!function db_success(index){
    _db.executeSql(json.dados[index], [], function (tx, res){
        if (index === (tamanho - 1)) {
            Funcoes.alerta('Último registro foi processado');
            myApp.hidePreloader();
        }
    })
}(i), 
function (t,e){
    Funcoes.alerta('Error: '+nome[1]+' '+e.message,'Aviso');
});
  • Worked by the tip but already tried so the problem is the following, first he is reading all the for(), and then he inserts, for example if I put the way you quoted var i is already at the maximum size, why? Because it first reads all the for() and then it enters the _db.executeSQL() block... To illustrate better I debugged it.. I put the console.log(i) inside the for, and another inside the success result, then I realized that it will display everything in for and then last...

  • I didn’t notice the loop with asynchronous function. I fixed the code using an immediate function. The value of i is already at the most why the call to _db.executeSql is asynchronous, so it returns immediately and the i reaches maximum value before processing is complete.

  • Hmm, so now there’s this mistake.. Uncaught Referenceerror: Tx is not defined -- Line 221, and in this line 221 is this excerpt... (Function (Tx, res, index){ if (index === (size - 1)) { console.log("Populating: "+tbl); console.log('Last record processed'); myapp.hidePreloader(); } })(Tx, res, i),

  • I threw the function out of the executeSql, but there is no way I can run the code here to check. I believe that the tx is not defined thus.

  • So, I put this function inside the loop, this is the right one? In case now it is giving error saying that it is missing a lock of keys in the code... Another thing, the variable within the parentheses of the function (index) I need to put a variable i ? or do not need? I want to thank you again for your help!

  • So, I missed closing a parentheses, I fixed the code. The parameter index of function db_success(index) will take on the value of i, you don’t have to change anything there.

  • now appeared the error: Uncaught Syntaxerror: Unexpected token ) this error is in the last line of code that is }); Function (t, e) should not be inside _db ? because it shows an error if the insertion is not right...

  • I changed the code to this form, http://jsfiddle.net/bpaacsh1/ That’s correct?

  • Yes. I created a Fork http://jsfiddle.net/1nya4vc2/ where I only changed the function notation (changed the ! parentheses).

  • Tulio, I put, even so of the error of closing parentheses.. I edited my main code, I put it complete for you to see. I’m using anoonimas functions, I don’t know if it has anything to do with this...

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.