I'm trying to get data from firebase and it worked with once().then function, but the problem is when I save the data a variable, its value will change only inside the function ( when the execution of the function is finished then the variable will not have the returned value from firebase )
code example :
static var temp = [];
void tempp() {
var db = FirebaseDatabase.instance.reference();
db.once().then((DataSnapshot snapshot) {
temp.add(1);
print(temp[0]);
});
print(temp[0]);
}
So, the first print statement will print the new value in temp list which is at index zero
but for the second print ( outside the once().then function ) will cause value range error
Invalid value: Valid value range is empty: 0
that means the value that was saved in the function it is not there anymore
How can I save the value after function is executed ?
I tried to use global variables it didn't work,
your help is much appreciated.
thank you.
Related
I'm developing apps by flutter/moor.
but I don't get how to write custom query which returns Future<List> class object.
I could wrote query which returns Stream class object.
but it's not enough.
does anyone now how to change it to one which returns Future class.
query I wrote is bellow
db.dart
Stream<List<QuestionHeader>> selectQuestionHeaderByKey(int businessYear,int period, int questionNo) {
return
customSelect(
'SELECT *'
+'From question_Headers '
+'WHERE business_Year = ? '
+'AND period = ? '
+'AND question_No = ?;',
variables: [Variable.withInt(businessYear),Variable.withInt(period),Variable.withInt(questionNo)],
readsFrom: {questionHeaders},
).watch().map((rows) {
return rows
.map((row) => QuestionHeader(
businessYear:row.readInt('businessYear')
,period:row.readInt('period')
,questionNo:row.readInt('questionNo')
,subjectId:row.readInt('subjectId')
,compulsoryType:row.readInt('compulsoryType')
,answerType:row.readInt('answerType')
,questionText:row.readString('questionText')
,numberAnswer:row.readInt('numberAnswer')
,correctType1:row.readInt('correctType1')
,correctType2:row.readInt('correctType2')
,correctType3:row.readInt('correctType3')
,favorite:row.readBool('favorite')
)).toList();
});
}
this works but I need Future<List> class to return.
I have two Datasource tables Projects and tt_records with a hours number field. There is a one to many relation between the Project and tt_records. I would like to display the total number of hours per project in a table. I am able to compute the total hours in server side function, how do I bind the total with a label on the UI. I am attempting to use the following in the binding on the field. I see the function is called through info statements in the console logs, however the value does not display on the UI clientgetProjHours(#datasource.item._key); following is the Client Script
function clientgetProjHours(key){
return (google.script.run.withSuccessHandler(function (key) {
console.info("received result");
}).getProjHours(key));
}
Following is the server side script
function getProjHours(key){
console.log ("In the function getProjHours (" + key +")");
var pRecords = app.models.Projects.getRecord(key);
console.log("Contents of " + pRecords);
var tRecords =pRecords.tt_record;
console.log("Contents of t Records" + tRecords);
var total = 0;
tRecords.forEach (function (item){
total += item.actuals;
});
console.log ("The result is: " + total);
return total;
}
Could you please suggest the best way to achieve this fuction.
Thank you very much for your help
key parameter in function (key) { is the result of the Server Script.
So you just need to replace:
function (key) {
With:
function (result)
Also replace:
console.info("received result");
With:
app.pages.[PageName].descendants.[LabelName].text = result;
But as it mentioned already Calculated Model should fit such use case better.
In my project, I must know first and last key of child to do something. I have query same below, I use 'i' to find first but I don't know how to get last key? Have any ways to set if Firebase query complete will do function with child_added? .In test, console.log(last) but is undefinded
var i = 0;
myDataRef.limitToLast(10).on('child_added', function (snapshot){
if( i == 0)
{
first = snapshot.key;
}
renderInfo(snapshot.key, snapshot.val(), 'new');
last = snapshot.key;
});
console.log(last)
I am using Swift in a project, and using SQLite.swift for database handling. I am trying to retrieve the most recent entry from my database like below:
func returnLatestEmailAddressFromEmailsTable() -> String{
let dbPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String
let db = Database("\(dbPath)/db.sqlite3")
let emails = db["emails"]
let email = Expression<String>("email")
let time = Expression<Int>("time")
var returnEmail:String = ""
for res in emails.limit(1).order(time.desc) {
returnEmail = res[email]
println("from inside: \(returnEmail)")
}
return returnEmail
}
I am trying to test the returned string from the above function like this:
println("from outside: \(returnLatestEmailAddressFromEmailsTable())")
Note how I print the value from both inside and outside of the function. Inside, it works every single time. I am struggling with the "from outside:" part.
Sometimes the function returns the correct email, but sometimes it returns "" (presumably, the value was not set in the for loop).
How can I add "blocking" functionality so calling returnLatestEmailAddressFromEmailsTable() will always first evaluate the for loop, and only after this return the value?
I have a global variable 'csId' of string type. In the code below under drawChart() function, in for loop, csID variable should be set to '1' by the modelLocator when i=0 and csId should be set to '2' by modelLocator when i=1.(considering lengh=2).
Alert in drawchart() (for csId) seems to be printing the right 'csid' values(both 1 and 2) but in the dataFunction() 'columnSeries_labelFunc' i am always getting the csId Alert value as '2' and never as '1'.
Please find the code below:
drawchart() function::
public function drawChart():void
{
var cs:ColumnSeries= new ColumnSeries();
var lenght:Number=AppModelLocator.getInstance().ctsModel.productSummary.getItemAt(0).collMgmtOfcList.length;
myChart.series = [cs];
var tempObj:Object;
for(csLoop=0;csLoop<lenght;csLoop++)
{
cs = new ColumnSeries();
this.csId= new String(String(AppModelLocator.getInstance().ctsModel.productSummary.getItemAt(0).collMgmtOfcList[csLoop]));
Alert.show("csId="+this.csId);
cs.id=this.csId;
cs.displayName = 'Exposure';
cs.dataFunction=columnSeries_labelFunc;
myChart.series[csLoop] = cs;
}
columnSeries_labelFunc() function::
private function columnSeries_labelFunc(series:Series, item:Object, fieldName:String):Object {
var col:Number=0;
Alert.show("value of csid in columnSeries_labelFunc="+this.csId);
if(fieldName == "yValue" && series.id==csId){
return(item.exposureUSDList[0]);
}else if(fieldName == "yValue" && series.id==csId) {
return(item.exposureUSDList[1]);
}else if(fieldName == "xValue"){
return(item.rptType);
}else
return null;
}
Please Help!!!
First: Assigning a value to a global variable repeatedly inside a loop is a bad idea. Nothing good will happen from that.
It's hard to tell from the context here, but the most likely reason that you're having this problem is that the flow of execution is as follows:
drawChart() executes synchronously, counting through each step in the loop, creating the ColumnSeries, which are each invalidated, meaning they will redraw on the next frame. The function ends, with csID at the last value it held.
The app goes into the next step in the elastic racetrack and validates the invalidated components.
columnSeries_labelFunc is called, with csID still holding the terminal value from the loop.
The end result being that columnSeries_labelFunc isn't called until you're already completely finished in drawChart.
The simplest fix would be to read the id that you're setting on the series in the label function, rather than relying on a global variable at all.