SetImageResources using View Binding - android-viewbinding

I try to bind my ImageView using the setImageResource but i got type mismatch error can someone help me please.
override fun onBindViewHolder(holder: RobotViewHolder, position: Int) {
val currentItem = robotList[position]
with(holder.binding) {
robotItemImageView.setImageResource = currentItem.imageResource
categoryNameTextView.text = currentItem.text1
}

You can do it this way,
with(holder.binding) {
robotItemImageView.setImageResource(currentItem.imageResource)
categoryNameTextView.text = currentItem.text1
}

Related

Android dataStore with flow not get update after edit

I'm use DataStore with flow but I cant get any update on the flow when editing DataStore.
Store.kt
private class IStore(private val context: Context): Store {
val eventIDKey = stringPreferencesKey("EventID")
override suspend fun setEventID(eventID: String) {
context.dataStoreSettings.edit { settings ->
settings[eventIDKey] = eventID
}
}
override fun getEventID(): Flow<String> {
return context.dataStoreSettings.data.map { settings -> settings[eventIDKey].orEmpty() }
}
}
and manipulate getEventID() with data from room database in event service
EventService.kt
fun getSelectedEventLive() = store.getEventID()
.onEach { Log.d("EventService", "income new event id $it") }
.flatMapConcat { if(it.isNotBlank()) eventDao.get(it) else flowOf(null) }
onEach called when I collect the data but when updated it's not called again and need to close and open the app to show the latest data
MainViewModel.kt
val selectedEvent = eventService.getSelectedEventLive()
.stateIn(viewModelScope, SharingStarted.Lazily, null)
and use on Compose with this
val currentEvent by mainViewModel.selectedEvent.collectAsState()
Maybe I doing wrong or maybe there is something I miss?
Usually, you want to use flow.collect {...}, since Flow is cold and need to know that it is being collected to start producing new values.
// MainViewModel.kt
private val _selectedEvent = MutableStateFlow<TypeOfYourEvent>()
val selectedEvent: StateFlow<TypeOfYourEvent> = _selectedEvent
init {
viewModelScope.launch {
getSelectedEventLive().collect { it ->
_selectedEvent.value = it
}
}
}
This example should be fine with your composable's code, you still can collect selectedEvent as state.
Yeah i found the solusion its works if i change the flatMapConcat with flatMapLatest in EventService.kt
fun getSelectedEventLive() = store.getEventID()
.filterNot { it.isBlank() }
.flatMapLatest { eventDao.get(it) }

Cannot convert value of type 'inout NSNumber?' to expected argument type 'AutoreleasingUnsafeMutablePointer<AnyObject?>' error

I have this script use to check whether the *downloaded file from iCloud is available or not. But unfortunately I encountered error Cannot convert value of type 'inout NSNumber?' to expected argument type 'AutoreleasingUnsafeMutablePointer<AnyObject?>' in some lines of code. Please help me to solve this issue because it is my first time to create a code to check whether the downloaded file is available in the icloud or not.
Please refer to the image below as sample of the error and also codes are available below for your reference. Hope you could help me. Thank you.
Sample screenshot of error
//-------------------------------------------------------------------
// ダウンロードできるか判定 Judgment or can be downloaded
//-------------------------------------------------------------------
func downloadFileIfNotAvailable(_ file: URL?) -> Bool {
var isIniCloud: NSNumber? = nil
do {
try (file as NSURL?)?.getResourceValue(&isIniCloud, forKey: .isUbiquitousItemKey)
if try (file as NSURL?)?.getResourceValue(&isIniCloud, forKey: .isUbiquitousItemKey) != nil {
if isIniCloud?.boolValue ?? false {
var isDownloaded: NSNumber? = nil
if try (file as NSURL?)?.getResourceValue(&isDownloaded, forKey: .ubiquitousItemIsDownloadedKey) != nil {
if isDownloaded?.boolValue ?? false {
return true
}
performSelector(inBackground: #selector(startDownLoad(_:)), with: file)
return false
}
}
}
} catch {
}
return true
}
It looks like you copied and pasted some really old code. Besides, this is Swift, not Objective-C. Do not use NSURL or getResourceValue. Your code should look more like this:
if let rv = try file?.resourceValues(forKeys: [.isUbiquitousItemKey]) {
if let isInCloud = rv.isUbiquitousItem {
// and so on
}
}
And so on; the same pattern applied to other keys. Note that there is no .ubiquitousItemIsDownloadKey either. You can condense things like this:
if let rv = try file?.resourceValues(
forKeys: [.isUbiquitousItemKey, .ubiquitousItemDownloadingStatusKey]) {
if let isInCloud = rv.isUbiquitousItem {
if let status = rv.ubiquitousItemDownloadingStatus {
if status == .downloaded {
}
}
}
}

Cannot call value of non-function type '((AnyClass) -> Bool)!'

here is my code.
let myDeepLinkAction: UAAction = UAAction(block: {(args:UAActionArguments, handler:UAActionCompletionHandler) -> Void in
handler(UAActionResult.empty())
}, acceptingArguments: {(arguments: UAActionArguments) in
if arguments.situation == UASituation.backgroundPush {
return true
}
return ((arguments.value! as AnyObject).isKind(of: NSString) || (arguments.value! as AnyObject).isKind(of: URL))
})
that type error is coming after swift version conversion 2.2 to 3.0,pls give me solution as possible.
I have found the solution,its simple
let myDeepLinkAction: UAAction = UAAction(block: {(args:UAActionArguments, handler:UAActionCompletionHandler) -> Void in
handler(UAActionResult.empty())
}, acceptingArguments: {(arguments: UAActionArguments) in
if arguments.situation == UASituation.backgroundPush {
return true
}
return (arguments.value! is NSString || arguments.value! is URL)
})
return (arguments.value! is NSString || arguments.value! is URL)
Make use of classForKeyedArchiver property
For eg : If you want to find out if a view controller belongs to a certain class , use the following snippet
if sampleController.isKind( of : listOfFlowersViewController.classForKeyedArchiver()!)
{
//your success code here
}
I was having this issue when I updated to swift 3 in xcode 8
for view in subViews {
if ((view as AnyObject).isKind(of : UIScrollView))
{
scrollView = view as? UIScrollView
}
It was showing error "Cannot call value of non-function type '((AnyClass) -> Bool)!"
Then I added this "classForKeyedArchiver()"
for view in subViews {
if ((view as AnyObject).isKind(of :
UIScrollView().classForKeyedArchiver!))
{
scrollView = view as? UIScrollView
}
Thanks a lot,it worked for me.

Any way to check and get NSLayoutConstraint conflicts programmatically?

EDIT: I updated the question so it is more clear.
Is there a way to check the constraints and get an NSArray of conflicting ones?
I'm working on an Autolayout helper class and I would like to print a pretty log when there are conflicts or errors.
By default, when there are layout conflicts you get a log that shows the conflicting constraints like this:
"<NSLayoutConstraint:0x7fe110638610 UILabel:0x7fe11062bb80'green'.leading == UIView:0x7fe11070de50.leadingMargin>",
"<NSLayoutConstraint:0x7fe1106386b0 H:[UILabel:0x7fe11062bb80'green'(20)]>",
"<NSLayoutConstraint:0x7fe110638660 UIView:0x7fe11070de50.trailingMargin == UILabel:0x7fe11062bb80'green'.trailing>",
"<NSLayoutConstraint:0x7fe11063fbe0 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7fe11070de50(375)]>"
I would like to get those constraints to display them in a prettier way (by view key for example). Any idea on how to do it?
Thanks!
My book provides a couple of utility methods (implemented in a category on NSLayoutConstraint) that I like to use to log constraints when I'm debugging or exploring them:
extension NSLayoutConstraint {
class func reportAmbiguity (var v:UIView?) {
if v == nil {
v = UIApplication.sharedApplication().keyWindow
}
for vv in v!.subviews as! [UIView] {
println("\(vv) \(vv.hasAmbiguousLayout())")
if vv.subviews.count > 0 {
self.reportAmbiguity(vv)
}
}
}
class func listConstraints (var v:UIView?) {
if v == nil {
v = UIApplication.sharedApplication().keyWindow
}
for vv in v!.subviews as! [UIView] {
let arr1 = vv.constraintsAffectingLayoutForAxis(.Horizontal)
let arr2 = vv.constraintsAffectingLayoutForAxis(.Vertical)
NSLog("\n\n%#\nH: %#\nV:%#", vv, arr1, arr2);
if vv.subviews.count > 0 {
self.listConstraints(vv)
}
}
}
}

Code error in Tic-Tac-Toe game

I would really appreciate your help with the following. I have been battling this small nuisance for a while now but without luck. I have this bit of code thats basically simulates a AI playing TIC TAC TOE against a player.
let Result = RowCheck(value: 0)
if Result != nil {
println("Computer has two in a row")
var WhereToPlayResult = WhereToPlay(Result.location, pattern: Result.pattern)
if !IsOccupied(WhereToPlayResult) {
SetImageForSpot(WhereToPlayResult, player: 0)
aiDeciding = false
CheckForWin()
return
}
return
}
RowCheck just checks for a pattern to play against.
func RowCheck(#‎value:Int) -> (location:String,pattern:String)? {
var AcceptableFinds = ["011","110","101"]
var FindFuncs = [CheckTop,CheckBottom,CheckLeft,CheckRight,CheckMiddleAcross,CheckMiddleDown,CheckDiagionalRightLeft,CheckDiagionalLeftRight]
for Algorthm in FindFuncs {
var AlgorthmResults = Algorthm(value:value)
if (find(AcceptableFinds,AlgorthmResults.pattern) != nil) {
return AlgorthmResults
}
}
return nil
}
But it gives me an error at:
var WhereToPlayResult = WhereToPlay(Result.location, pattern: Result.pattern)
Because your RowCheck method returns an optional (and might return nil), you need to either unwrap your optional or use a different assignment:
let Result = RowCheck(value: 0)
if Result != nil {
var WhereToPlayResult = WhereToPlay(Result!.location, pattern: Result!.pattern)
// ... ^ ^
}
if let Result = RowCheck(value: 0) {
// ...
}
Side note: only classes should be named starting with a capital letter. To stay within Apple's code style, you should variables and functions as result, rowCheck, etc.

Resources