Read database into array wont work anymore.. did in another example before... wierd

Like the title implies, somehow this wont read my table into my array

var names = ;
var age = ;
readRecords(“Testdata”, {}, function(records) {
for (var i =0; i < records.length; i++) {
appendItem(names, (records[i]).Row1);
appendItem(age, (records[i]).Row2);
setText(“label_name”, names[0]);
setText(“label_age”, age[0]);

I did check if I refere to the right table…

That particular code won’t work because the callback function in readRecords is going to be called after the two setText calls. You will see undefined in both of the labels because the database has not been accessed yet. You will need to include the calls to setText in the callback or somehow signal when the callback function is done.

thanks for the respons, wierd thing anyway, since I use same build in a much older app i made. I have been looking into this problem further and when I set down the speed to turtle, it actually works. wierd…

I have done these multiple times before, but never encountered such a problem before. Here is a temporary workarround:

thanks for your reply :slight_smile:

That should work. The only time it wouldn’t is if the database is very large or your internet connection is slow. It works because the database loads faster than a person clicking. That is fine, no one will notice.

If you are interested in making it fool proof continue reading:

Try this. Open your project. Reload it. (Database is cached.) Run it. Disconnect your internet. Click the first button. Click the second button. You get an error.

The reason for that is there is still nothing to keep the user from clicking on the second button before the database has finished loading. To avoid that we need some way to wait till the database is loaded before we press that second button. We can do that by hiding it and only showing it after the database is loaded. Look at this:

What I have done is put showElement("button2"); into the database callback. If I then make that button hidden to start with it will show up after the database is done loading. I put 5000 records into the database so you see it pop up after a second.

You can unhide the button, reload, run and click the buttons fast. You will get an error. Again, because it hasn’t finished loading. (Mostly it is filling the Array that takes all the time. Directly using the Array and JSON objects that are returned is faster.)

Here is another thread that looks at App Lab databases and faulty connections Does update/read/createRecord return an error where there's a timeout?