Uncaught Kotlin exception: kotlin.native.IncorrectDereferenceException: - kotlin

I'm still relatively new to KMM and a project I'm working on keeps yeilding this error:
Uncaught Kotlin exception: kotlin.native.IncorrectDereferenceException: illegal attempt to access non-shared dev.mrbe.haarShared.HaarSDK#abc468 from other thread
at 0 kotlinmultiplatformsharedmodule 0x00000001020909a1 kfun:kotlin.Throwable#<init>(kotlin.String?){} + 97 (/opt/buildAgent/work/c5a36d4d82b914cf/kotlin/kotlin-native/runtime/src/main/kotlin/kotlin/Throwable.kt:24:56)
at 1 kotlinmultiplatformsharedmodule 0x0000000102089dad kfun:kotlin.Exception#<init>(kotlin.String?){} + 93 (/opt/buildAgent/work/c5a36d4d82b914cf/kotlin/kotlin-native/runtime/src/main/kotlin/kotlin/Exceptions.kt:23:58)
at 2 kotlinmultiplatformsharedmodule 0x0000000102089fcd kfun:kotlin.RuntimeException#<init>(kotlin.String?){} + 93 (/opt/buildAgent/work/c5a36d4d82b914cf/kotlin/kotlin-native/runtime/src/main/kotlin/kotlin/Exceptions.kt:34:58)
at 3 kotlinmultiplatformsharedmodule 0x00000001020c140d kfun:kotlin.native.IncorrectDereferenceException#<init>(kotlin.String){} + 93 (/opt/buildAgent/work/c5a36d4d82b914cf/kotlin/kotlin-native/runtime/src/main/kotlin/kotlin/native/Runtime.kt:31:50)
at 4 kotlinmultiplatformsharedmodule 0x00000001020c508f ThrowIllegalObjectSharingException + 623 (/opt/buildAgent/work/c5a36d4d82b914cf/kotlin/kotlin-native/runtime/src/main/kotlin/kotlin/native/concurrent/Internal.kt:115:11)
at 5 kotlinmultiplatformsharedmodule 0x00000001022a1b52 _ZN12_GLOBAL__N_128throwIllegalSharingExceptionEP9ObjHeader + 34
at 6 kotlinmultiplatformsharedmodule 0x00000001022a389d _ZN12_GLOBAL__N_136terminateWithIllegalSharingExceptionEP9ObjHeader + 13
at 7 kotlinmultiplatformsharedmodule 0x00000001022a39b5 _ZNK27BackRefFromAssociatedObject3refIL11ErrorPolicy3EEEP9ObjHeaderv + 133
at 8 kotlinmultiplatformsharedmodule 0x0000000102070e25 -[KotlinBase toKotlin:] + 21
at 9 kotlinmultiplatformsharedmodule 0x0000000102295058 Kotlin_ObjCExport_refFromObjC + 88
at 10 kotlinmultiplatformsharedmodule 0x0000000102040676 objc2kotlin.505 + 230
at 11 haar 0x00000001006b3181 $s4haar11MyViewModelC10addBooking7bookingySo031KotlinmultiplatformsharedmoduleF0C_tYaFTY0_ + 273 (/Users/essienedim/Desktop/HAAR /haar/haar/ContentView.swift:422:33)
at 12 libswift_Concurrency.dylib 0x00007ff833c40426 _ZN5swift34runJobInEstablishedExecutorContextEPNS_3JobE + 310
at 13 libswift_Concurrency.dylib 0x00007ff833c411bd _ZL17swift_job_runImplPN5swift3JobENS_11ExecutorRefE + 77
at 14 libdispatch.dylib 0x00000001014dfe77 _dispatch_continuation_pop + 87
at 15 libdispatch.dylib 0x00000001014def27 _dispatch_async_redirect_invoke + 997
at 16 libdispatch.dylib 0x00000001014f1e77 _dispatch_root_queue_drain + 414
at 17 libdispatch.dylib 0x00000001014f2b17 _dispatch_worker_thread2 + 278
at 18 libsystem_pthread.dylib 0x00007ff833e39f8a _pthread_wqthread + 256
at 19 libsystem_pthread.dylib 0x00007ff833e38f57 start_wqthread + 15
CoreSimulator 857.7 - Device: iPhone 14 Pro (C24AA3AD-B79D-437E-BCB7-A15C83C0F412) - Runtime: iOS 16.0 (20A360) - DeviceType: iPhone 14 Pro
(lldb)
I have seen this and some other posts on this but when I try using the freeze() method, I keep getting an Unresolved reference: freeze. I can't seem to figure out what exactly I'm doing wrong and honestly, what I should be freezing exactly.
Here's the function that seems to be triggering this Exception:
func addBooking(booking: Booking) async {
await sdk.postBooking(booking: booking)
}
The SDK class is initialise in the view model like so:
class MyViewModel: ObservableObject {
let sdk: HaarSDK
...
init(sdk: HaarSDK) {
self.sdk = sdk
...
}
}
Main View:
struct MainView: View {
#StateObject private var viewModel: MyViewModel
init() {
let sdk = HaarSDK(databaseDriverFactory: DatabaseDriverFactory())
let viewModel = MyViewModel(sdk: sdk)
_viewModel = StateObject(wrappedValue: viewModel)
}
...
}
SDK class (Kotlin):
class HaarSDK(databaseDriverFactory: DatabaseDriverFactory) {
private val database = Database(databaseDriverFactory)
private val api = HaarApi()
...
#Throws(Exception::class)
suspend fun postBooking(booking: Booking) {
api.sendBooking(booking)
}
...
}
Database:
internal class Database(databaseDriverFactory: DatabaseDriverFactory) {
private val database by lazy {
AppDatabase(databaseDriverFactory.createDriver())
}
private val dbQuery = database.appDatabaseQueries
...
}
API class:
class HaarApi {
private val httpClient = HttpClient {
install(JsonFeature) {
val json = Json { ignoreUnknownKeys = true }
serializer = KotlinxSerializer(json)
}
...
suspend fun sendBooking(booking: Booking) {
val response: HttpResponse = httpClient.post(BOOKING_ENDPOINT) {
contentType(ContentType.Application.Json)
body = booking
}
...
}

Related

Basic Kotlin , Basic Kotlin Android Development

> 1 package com.linecorp.exam
> 2
> 3 import android.os.Bundle
> 4 import android.widget.TextView
> 5 import android.app.Activity
> 6 import android.graphics.Color
> 7 import android.view.Gravity
> 8 import android.view.View
> 9 import android.view.ViewGroup
> 10 import android.widget.BaseAdapter
> 11 import android.widget.ListView
> 12
> 13 class MainActivity : Activity() {
> 14
> 15 enum class taskstate {
> 16 todo,
> 17 done
> 18 }
> 19
> 20 var tasklist = mutableListOf<Pair<String, taskstate>>()
> 21
> 22 private lateinit var myadapter: Myadapter
> 23
> 24 override fun onCreate(savedInstanceState: Bundle?) {
> 25 super.onCreate(savedInstanceState)
> 26 setContentView(R.layout.activity_main)
> 27
> 28 myadapter = Myadapter()
> 29 val listView = findViewById<ListView>(R.id.list_view)
> 30 listView.adapter = myadapter
> 31
> 32 tasklist.clear()
> 33 var i = 0
> 34 todoRepository.instance.fetch_all().forEach { t ->
> 35 tasklist.add(i++, t)
> 36 myadapter.notifyDataSetChanged()
> 37 }
> 38 }
> 39
> 40 override fun onDestroy() {
> 41 tasklist.clear()
> 42 }
> 43
> 44 inner class Myadapter : BaseAdapter() {
> 45
> 46 private lateinit var convertView: View
> 47
> 48 override fun getCount(): Int {
> 49 return tasklist.size
> 50 }
> 51
> 52 override fun getItem(position: Int): Any {
> 53 val li = tasklist.filter { it.second == taskstate.todo } +
> 54 tasklist.filter { it.second == taskstate.done }
> 55 return li[position]
> 56 }
> 57
> 58 override fun getItemId(position: Int): Long {
> 59 return 0
> 60 }
> 61
> 62 override fun getView(position: Int, convertView: View?, container: ViewGroup?): View {
> 63 this.convertView = if (convertView == null) {
> 64 layoutInflater.inflate(R.layout.list_item, container, false)
> 65 } else {
> 66 convertView
> 67 }
> 68
> 69 val i = getItem(position) as Pair<String, taskstate>
> 70 this.convertView.findViewById<TextView>(R.id.item_label)
> 71 .apply {
> 72 when (i.second) {
> 73 taskstate.todo -> {
> 74 setText("TODO")
> 75 setBackgroundColor(Color.YELLOW)
> 76 }
> 77 else -> {
> 78 setText("DONE")
> 79 }
> 80 }
> 81 }
> 82 this.convertView.findViewById<TextView>(R.id.item_text)
> 83 .setText(i.first)
> 84
> 85 return convertView!!
> 86 }
> 87 }
> 88 }`enter code here`
This was a question I got when I appeared for an test. Unfortunately I failed :) The question was how to improve this Kotlin Android code and add necessary comments if needed. (please dont consider this line ipsum dfgsdndd gfnjfn vjfnvkf fjnvkfv vnkdkvd dndk. sds dshdsd shdahd sdiauhd basudsua saudhaus sahdsuahd ashdoahsd shdoahd ashdosahd asdhoaishd )
The problem here is you are returning total if s1<s2 while that's not the case. Even if you find one such case, that's not the end of string, you should continue processing. Instead of returning, you should increment i to i+2 as you have already processed i+1. Since you can't do such increment in between a for loop, so you will have to go with a while loop.
fun romanToInt(s: String): Int {
val map = mapOf('I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000)
var total = 0
var i = 0
while (i < s.length) {
val current = map[s[i]]!!
val next = if (i != s.lastIndex) map[s[i + 1]]!! else 0
if (current >= next) {
total += current
i++
} else {
total += next - current
i += 2
}
}
return total
}

sigsegv compilation error of simple kotlin code

Following code generates error which looks like an error in compiler, its has nothing to do with the kotlin code, or maybe I am missing something? I have JDK error on macos and some more informative error (like pasted at the end of this post) from online compiler. How can I fix it?
Code: https://pl.kotl.in/CfdXHeDyn
import kotlin.math.pow
fun calculateNumberOfContainers(data: String): Int {
val containerSizes = mutableListOf<Int>()
data.lines().forEach { containerSizes.add(it.toInt()) }
var foundCorrect = 0
val maxSubSets = (2.0).pow(20).toULong()
for (n in 0UL until maxSubSets) {
var total = 0
for (k in 0 until 20) {
val mask = 1UL shl k
if ((mask and n) != 0UL) {
total += containerSizes[k]
if (total > 150)
break
}
}
if (total == 150)
foundCorrect++
}
return foundCorrect
}
fun runcode() {
val data =
"""
33
14
18
20
45
35
16
35
1
13
18
13
50
44
48
6
24
41
30
42
""".trimIndent()
calculateNumberOfContainers(data)
}
fun main() {
runcode()
}
Error:
Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unexpected character ('#' (code 35)): was expecting double-quote to start field name
at [Source: (String)"{#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007fc646ef2eba, pid=1900, tid=0x00007fc6307f7700
#
# JRE version: OpenJDK Runtime Environment (8.0_201-b09) (build 1.8.0_201-b09)
# Java VM: OpenJDK 64-Bit Server VM (25.201-b09 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# V [libjvm.so+0x382eba]
#
# Core dump written. Default location: /var/task/core or core.1900
#
# An error report file with more information is saved as:
# /tmp/"[truncated 195 chars]; line: 1, column: 3]
at com.fasterxml.jackson.core.JsonParser._constructError (JsonParser.java:1851)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError (ParserMinimalBase.java:707)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar (ParserMinimalBase.java:632)
Update:
it works with 1.4.30, fails with 1.5.21, so its a bug in compiler
I changed from Unsigned Long to Unsigned Int and problem went away, code after changes looks as follows:
https://pl.kotl.in/XedacixZK
import kotlin.math.pow
fun calculateNumberOfContainers(data: String): Int {
val containerSizes = mutableListOf<Int>()
data.lines().forEach { containerSizes.add(it.toInt()) }
var foundCorrect = 0
val maxSubSets = (2.0).pow(20).toUInt()
for (n in 0U until maxSubSets) {
var total = 0
for (k in 0 until 20) {
val mask = 1U shl k
if ((mask and n) != 0U) {
total += containerSizes[k]
if (total > 150)
break
}
}
if (total == 150)
foundCorrect++
}
return foundCorrect
}
fun runcode() {
val data =
"""
33
14
18
20
45
35
16
35
1
13
18
13
50
44
48
6
24
41
30
42
""".trimIndent()
print(calculateNumberOfContainers(data))
}
fun main() {
runcode()
}

Get CGRect of View

I'm using a "RectGetter" to get the CGRect of a View.
Like this:
Text("Hello")
.background(RectGetter(rect: self.$rect))
struct RectGetter: View {
#Binding var rect: CGRect
var body: some View {
GeometryReader { proxy in
self.createView(proxy: proxy)
}
}
func createView(proxy: GeometryProxy) -> some View {
DispatchQueue.main.async {
self.rect = proxy.frame(in: .global) // crash here
}
return Rectangle().fill(Color.clear)
}
}
But sometimes I get a crash when setting the rect.
Thread 0 name:
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x00000001a1ec5ec4 __pthread_kill + 8
1 libsystem_pthread.dylib 0x00000001a1de5724 pthread_kill$VARIANT$armv81 + 216 (pthread.c:1458)
2 libsystem_c.dylib 0x00000001a1d358c0 __abort + 112 (abort.c:147)
3 libsystem_c.dylib 0x00000001a1d35850 abort + 112 (abort.c:118)
4 AttributeGraph 0x00000001cce56548 0x1cce25000 + 202056
5 AttributeGraph 0x00000001cce2b980 0x1cce25000 + 27008
6 SwiftUI 0x00000001d89ce9b4 $s7SwiftUI27_PositionAwareLayoutContextV10dimensionsSo6CGSizeVvg + 56 (<compiler-generated>:0)
7 SwiftUI 0x00000001d8a43584 $sSo6CGSizeVIgd_ABIegr_TRTA + 24 (<compiler-generated>:0)
8 SwiftUI 0x00000001d8a43a54 $s7SwiftUI13GeometryProxyV4sync33_4C4BAC551E328ACCA9CD3748EDC0CC3ALLyxSgxyXElFxAA9ViewGraphCXEfU_... + 92 (GeometryReader.swift:126)
9 SwiftUI 0x00000001d8a43f20 $s7SwiftUI13GeometryProxyV4sync33_4C4BAC551E328ACCA9CD3748EDC0CC3ALLyxSgxyXElFxAA9ViewGraphCXEfU_... + 20 (<compiler-generated>:0)
10 SwiftUI 0x00000001d8c4842c $s7SwiftUI16ViewRendererHostPAAE06updateC5Graph4bodyqd__qd__AA0cG0CXE_tlF + 80 (ViewRendererHost.swift:64)
11 SwiftUI 0x00000001d8a438d4 $s7SwiftUI13GeometryProxyV5frame2inSo6CGRectVAA15CoordinateSpaceO_tF + 196 (GeometryReader.swift:125)
12 MyApp 0x0000000102cf5c54 closure #1 in RectGetter.createView(proxy:) + 128 (RectGetter.swift:22)
Is there some more reliable way (not crashing) to get the CGRect of a View?
Update: improved and simplified a possible solution to read rect of any view in any coordinate space via helper extension. Works since Xcode 11.1, retested with Xcode 13.3.
Main part:
func rectReader(_ binding: Binding<CGRect>, _ space: CoordinateSpace = .global) -> some View {
GeometryReader { (geometry) -> Color in
let rect = geometry.frame(in: space)
DispatchQueue.main.async {
binding.wrappedValue = rect
}
return .clear
}
}
Usage the same
Text("Test").background(rectReader($rect))
or with new extension
Text("Test").reading(rect: $rect)
Complete findings and code is here
Another way is with Preference Keys, as outlined here.
In summary, you can set up a modifier:
struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGRect = .zero
static func reduce(value: inout CGRect, nextValue: () -> CGRect) {
value = nextValue()
}
}
struct SizeModifier: ViewModifier {
private var sizeView: some View {
GeometryReader { geometry in
Color.clear.preference(key: SizePreferenceKey.self, value: geometry.frame(in: .global))
}
}
func body(content: Content) -> some View {
content.background(sizeView)
}
}
Then use that one:
SomeView()
.modifier(SizeModifier())
.onPreferenceChange(SizePreferenceKey.self) { print("My rect is: \($0)") }

Illegal start of expression in jcreator

I am not sure why there is an error, which keeps on saying that there is an illegal start of expression and ')' is expected error. It occurs in line 14.
1 import java.io.*;
2 public class LeapYear{
3 public static void main(String[] args){
4 String leapYear="";
5 int intleapYear;
6
7 BufferedReader input = new BufferedReader(
8 new InputStreamReader(System.in));
9
10 try{
11 System.out.print("Enter a year: " +leapYear);
12 leapYear=input.readLine();
13 intleapYear=Integer.parseInt(leapYear);
14 boolean isleapyear= ((intleapYear%4==0)&&(intleapYear%100!==0)||(intleapYear%400==0));
16
17
18 if(isleapyear){
19 System.out.println(intleapYear + " is a leap year.");
20 } else
21 System.out.println(intleapYear + " is not a leap year.");
22
23 }catch(IOException e){
24 System.out.println("Error");
25 }
26
27
28
29
30 /*if ((intleapYear%4==0)&&(intleapYear%100!==0)||(intleapYear%400==0)){
31 System.out.println(intleapYear+" is a leap year.");
32 }else
33 System.out.println(intleapYear+" is not a leap year.");*/
}
}
It is because you are using !==
you should use !=
so line 14 would be:
boolean isleapyear= ((intleapYear%4==0)&&(intleapYear%100!=0)||(intleapYear%400==0));

j2objc object serialization -- java.lang.NoSuchMethodException: writeReplace

Update - You can find a sample project to recreate the issue here: https://github.com/benf1977/j2objc-serialization-example/releases/tag/1.0
I'm trying to serialize an object in Java and pass the bytes over to my Objective-C layer to write to the filesystem. My relevant Java code is this:
/**
* Created by benjamin.flynn on 10/7/15.
*/
public class TestData implements Serializable {
private String mName;
private int mAge;
public TestData(String pName, int pAge) {
mName = pName;
mAge = pAge;
}
public String getName() {
return mName;
}
public int getAge() {
return mAge;
}
public byte[] bytes() {
byte[] bytes = null;
try (ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream);) { // Application will break on this line when run on Xcode
objectOutputStream.writeObject(this);
bytes = byteOutputStream.toByteArray();
} catch (IOException ioe) {
System.err.println("Aww snap: " + ioe);
}
return bytes;
}
}
I've unit tested this class in Java (which I also have a deserializer for) and it passes. In Objective-C, I'm doing this:
ComMycompanyTestData *testData = [[ComMycompanyTestData alloc] initWithNSString:#"Daryl" withInt:47];
IOSByteArray *bytes = testData.bytes; // Exception here
The exception is:
(lldb) po $arg1
java.lang.NoSuchMethodException: writeReplace
The relevant trace is:
frame #0: 0x000000019a2cbf48 libobjc.A.dylib`objc_exception_throw
frame #1: 0x0000000100214bb0 MyApp `-[IOSClass getDeclaredMethod:parameterTypes:] + 124
frame #2: 0x00000001000c9188 MyApp`JavaIoObjectStreamClass_findMethodWithIOSClass_withNSString_ + 144
frame #3: 0x00000001000c71dc MyApp`JavaIoObjectStreamClass_createClassDescWithIOSClass_ + 984
frame #4: 0x00000001000c909c MyApp`JavaIoObjectStreamClass_lookupStreamClassWithIOSClass_ + 88
frame #5: 0x00000001000c8f88 MyApp`JavaIoObjectStreamClass_lookupWithIOSClass_ + 44
frame #6: 0x00000001000c6f30 MyApp`JavaIoObjectStreamClass_createClassDescWithIOSClass_ + 300
frame #7: 0x00000001000c909c MyApp`JavaIoObjectStreamClass_lookupStreamClassWithIOSClass_ + 88
frame #8: 0x00000001000c8f88 MyApp`JavaIoObjectStreamClass_lookupWithIOSClass_ + 44
frame #9: 0x00000001000c284c MyApp`JavaIoObjectOutputStream_initWithJavaIoOutputStream_ + 56
frame #10: 0x00000001000c6a20 MyApp`new_JavaIoObjectOutputStream_initWithJavaIoOutputStream_ + 48
* frame #11: 0x00000001000a666c MyApp`-[ComMycompanyTestData bytes](self=0x000000013fd51a50, _cmd="bytes") + 76 at TestData.java:49
Thoughts on what might be happening?
What version of j2objc are you using? We've made recent improvements in serialization, and running your example works after adding this test added:
public static void main(String[] args) {
TestData td = new TestData("Jane Doe", 30);
byte[] serialized = td.bytes();
System.out.println("serialized: " + Arrays.toString(serialized));
}
I ran this with a translator/runtime built using "make dist" on the current j2objc source:
$ javac TestData.java
$ java TestData
serialized: [-84, -19, 0, ...
$ j2objc TestData.java
translating TestData.java
Translated 1 file: 0 errors, 0 warnings
$ j2objcc TestData.m
$ ./a.out TestData
serialized: [-84, -19, 0, ...