Room DAO function always returns null - Solved.. I forget .start() for thread. :-) - sqlite

I have a DAO function as
Blockquote
#Query("SELECT DISTINCT name as pname FROM bevlista ORDER BY 1")
fun getaruk():MutableList<Product
Blockquote
and a class as
data class Product (
#ColumnInfo(name = "pname") var pname:String
)
When I test the Query in App Inspector , then the query result real :
Inspector
But when I call this funtion in the program then the result (test) is always null...
Debug
The test code in the rutin :
var test= mutableListOf<Product>() //=mutableListOf<Product>()
var szalt = Thread {
test = AppDatabase.getInstance(this#MainActivity).gradeDao().getaruk()
runOnUiThread {
println("breakpoint")
}
}
while(szalt.isAlive)
{Thread.sleep(10)}
println("breakpoint")
Can somebody help me to understand? Thanks in advance...

Related

I try to fetch data from firbase but I get this error.The method '[]' can't be unconditionally invoked because the receiver can be 'null'

'''
QuestionModel getQuestionModelFromDatasnapshot(
DocumentSnapshot questionSnapshot) {
QuestionModel questionModel = new QuestionModel();
questionModel.question = questionSnapshot.data()'question'];
List<String> options = [
questionSnapshot.data()["option1"],
questionSnapshot.data()["option2"],
questionSnapshot.data()["option3"],
questionSnapshot.data()["option4"]
];
options.shuffle();
questionModel.option1 = options[0];
questionModel.option2 = options[1];
questionModel.option3 = options[2];
questionModel.option4 = options[3];
questionModel.correctOption = questionSnapshot.data()["option1"];
questionModel.answered = false;
print(questionModel.correctOption.toLowerCase());
return questionModel;
}
'''
It looks like you're using dart with null safety on and you are accessing a list or map that might be null. It's hard to tell from your code, but I'm guessing the offending line is
questionModel.correctOption = questionSnapshot.data()["option1"];
It might be one of the other [] calls earlier in your code (such as
questionSnapshot.data()["option1"]), but the solution is the same.
The problem is that questionSnapshot.data() might return null, and the compiler is flagging it.
If you are sure the data is not null, you can use the ! operator, like this:
questionModel.correctOption = questionSnapshot.data()!["option1"];
Another solution is a conditional null-safe operator ?, with a default value. In this case, the code would look like this:
questionModel.correctOption = questionSnapshot.data()?["option1"]??"DefaultValue;
But I would recommend checking if the returned data is null. It's easier for others to read and can be logged more easily:
var data = questionSnapshot.data();
if (data != null) {
questionModel.correctOption = data["option1"];
}
else {
//do something in that case
}

how to write costomselect query which returns Future in Flutter/moor

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.

How to create nested GraphQL fields with Sangria's `#GraphQLField` annotation

I have a simple case class MyContext(queries: Query) that I provide to the schema with : sangria.schema.Schema(deriveContextObjectType[MyContext, Query, Unit](_.queries)
MyQuery is a trait of Query
trait MyQuery {
#GraphQLField
def item(ctx: Context[MyContext, Unit])(id: String) ...
}
This works great. But what if I want to nest resolvers?
query {
item {
status # status is resolved from source B
price # price is resolved from source C
}
}
Is that possible to achieve? Would I return an ObjectType[Item] that has properties status and price annotated with #GraphQLField?
I think you can use deriveObjectType for an Item. It is also able to handle the #GraphQLField annotation (as an alternative you can also use IncludeMethods macro setting). Here is an example:
implicit val ItemType = deriveObjectType[MyContext, Item]()
Really appreciate #tenshi's answer! I tried using the deriveObjectType but was getting a type error:
type mismatch;
found : sangria.schema.Context[MyContext,Item]
required: sangria.schema.Context[MyContext,Unit]
But using deriveContextObjectType in conjunction with AddFields is working:
def schema = sangria.schema.Schema(
deriveContextObjectType[MyContext, Query, Unit](_.queries,
AddFields(
Field(
name = "item",
fieldType = deriveContextObjectType[MyContext, Item, Unit](_ => new Item),
resolve = _ => ()
)
))
)
And the Schema looks good, yielding:
type Query {
item: Item!
}

Swift get value from UnsafeMutablePointer<Void> using UnsafePointer<String>

I am trying to pass contextInfo of typeUnsafeMutablePointer<Void> to UISaveVideoAtPathToSavedPhotosAlbum and use it in the callback function. For some reason I am unable to access contextInfo as a string using UnsafePointer<String>(x).memory when I am in the callback function.
I am pretty sure it is something simple I am missing but have spent way to many hours trying to figure this out.
Below is some code that I have tried.
The following code works.
var testStr:String = "hello"
takesAMutableVoidPointer(&testStr)
func takesAMutableVoidPointer(x: UnsafeMutablePointer<Void>){
var pStr:String = UnsafePointer<String>(x).memory
println("x = \(x)")
println("pStr = \(pStr)")
}
However the following code does not work.
var testStr:String = "hello"
if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(filePath){ //the filePath is compatible
println("Compatible")
//UISaveVideoAtPathToSavedPhotosAlbum(filePath, self, nil, nil)
UISaveVideoAtPathToSavedPhotosAlbum(filePath, self, "video:didFinishSavingWithError:contextInfo:", &testStr)
}
else{
println("Not Compatible")
}
func video(video: NSString, didFinishSavingWithError error:NSError, contextInfo:UnsafeMutablePointer<Void>){
var pStr:String = UnsafePointer<String>(contextInfo).memory
println("contextInfo = \(contextInfo)")
println("pStr = \(pStr)")
}
Once I get to the following line:
var pStr:String = UnsafePointer<String>(contextInfo).memory
I keep getting the following error:
Thread 1: EXC_BAD_ACCESS(code=1, address=0x0)
Any help with this would be greatly appreciated.
Thanks.
Update
Rintaro commented that testStr needs to be top level but the following code works.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var testStr:String = "hello"
takesAMutableVoidPointer(&testStr)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func takesAMutableVoidPointer(x: UnsafeMutablePointer<Void>){
var answer = UnsafePointer<String>(x).memory
println("x = \(x)")
println("answer = \(answer)")
}
}
I am trying not to use global variables unless I have to. I may have to but since I am able to execute the above code, it seems as though I do not need to use a global variable.
As discussed in OP comments, testStr has already been freed.
Is there any way to force the retaining of a variable that has been created in a function? Then release it later?
It's not impossible, but I don't know this is the best way to do that.
Anyway, try this with Playground or OS X "Command Line Tool" template:
import Foundation
func foo() {
var str:NSString = "Hello World"
let ptr = UnsafePointer<Void>(Unmanaged<NSString>.passRetained(str).toOpaque())
bar(ptr)
}
func bar(v:UnsafePointer<Void>) {
let at = dispatch_time(
DISPATCH_TIME_NOW,
Int64(2.0 * Double(NSEC_PER_SEC))
)
dispatch_after(at, dispatch_get_main_queue()) {
baz(v)
}
}
func baz(v:UnsafePointer<Void>) {
println("notified")
let str = Unmanaged<NSString>.fromOpaque(COpaquePointer(v)).takeRetainedValue()
println("info: \(str)")
}
foo()
println("started")
dispatch_main()
Unmanaged<NSString>.passRetained(str) increments the retain count.
Unmanaged<NSString>.fromOpaque(...).takeRetainedValue() decrements it, and extract the object.
I think, using pure Swift String is impossible. because String is struct and is allocated in stack memory. Maybe the buffer of it is allocated in heap, but we cannot access it directly.

How to pre-select an option in a dropdown knockout js

I've looked at this other question, but can't get my select box to work correctly:
Binding initial/default value of dropdown (select) list
I've got the following Game object:
function Game(visitingTeamDetails, homeTeamDetails, game) {
if (arguments.length > 0) {
this.VisitingTeamDetails = visitingTeamDetails;
this.HomeTeamDetails = homeTeamDetails;
this.GameId = ko.observable(game.GameId);
this.HomeTeamName = ko.observable(game.HomeTeamName);
this.VisitingTeamName = ko.observable(game.VisitingTeamName);
this.SportTypeName = ko.observable(game.SportTypeName);
this.HomeAccountName = ko.observable(game.HomeAccountName);
this.VisitingAccountName = ko.observable(game.VisitingAccountName);
this.GameDateString = ko.observable(game.GameDateString);
this.GameTimeString = ko.observable(game.GameTimeString);
this.AvailableSportTypes = ko.observableArray(game.Sports);
this.sportTypeFunction = function () {
for (sportType in this.AvailableSportTypes()) {
if (this.AvailableSportTypes()[sportType].Name == this.SportTypeName()) {
return this.AvailableSportTypes()[sportType];
}
}
return null;
};
this.SportType = ko.observable(game.SportType);
}
}
SportType is an object with Name and SportTypeId.
I have the following template:
<td rowspan="3"><select data-bind="options: AvailableSportTypes, value: SportType, optionsText:'Name', optionsCaption: 'Choose...'" class="sportType"></select></td>
AvailableSportTypes is a list of SportType.
The list is coming in with the names of the SportTypes in the drop down list, but I can't make the initial selection be SportType. I wrote sportTypeFunction to show myself that the data was coming in correctly, and it would select the correct value, but changing my selection in the drop down would not update SportType.
I'm sure I'm doing something wrong. Anyone see it?
Thanks
When game.SportType gets passed in, it needs to be a reference to the an item in the game.AvailableSportTypes and not just an object that looks the same.
Basically two objects are not equal unless they are actually a reference to the same object.
var a = { name: "test" },
b = { name: "test" };
alert(a === b); //false
So, you would need to call your function to locate the correct object in the array and set it as the value of your observable.
Not that it is way better, but in KO 1.3 you can extend .fn of observables, observableArrays, and dependentObservables to add additional functionality.
Here is a sample: http://jsfiddle.net/rniemeyer/ZP79w

Resources