yglukhov / jnim

Nim - Java bridge
MIT License
184 stars 13 forks source link

[Q] convert Nim string to android CharSequence? #55

Closed akavel closed 5 years ago

akavel commented 5 years ago

I'm trying to call Android's TextView.setText(...) method, which seems to take a java.lang.CharSequence (not java.lang.String) as an argument. This CharSequence is apparently (?) an interface implemented by java.lang.String. What should I do to successfully pass a Nim string to TextView.setText(...)?

I tried the following:

when defined android:
  import jnim
  import android/os/bundle
  import android/content/context
  import android/view/view
  import android/app/activity
  jclassDef java.lang.CharSequence of JVMObject
  jclass android.widget.TextView of JVMObject:
    proc new(c: Context)
    proc setText(s: CharSequence)

# ...

proc ...(jenv: JNIEnvPtr; jthis: jobject) {.cdecl, exportc, dynlib.} =
      let v = TextView.new(cast[MainActivity](jthis))
      v.setText("hello flappy nim")
      jthis.setContentView(v)

but I'm getting an error like below:

C:\prog\flappy-nim\src\flappy_nim.nim(44, 8) Error: type mismatch: got <TextView, string>
but expected one of:
proc setText(this: TextView; s: CharSequence)
  first type mismatch at position: 2
  required type for s: CharSequence
  but expression '"hello flappy nim"' is of type: string
1 other mismatching symbols have been suppressed; compile with --showAllMismatches:on to see them

expression: setText(v, "hello flappy nim")

Any ideas or thoughts?

yglukhov commented 5 years ago

I guess a blunt cast should work.

import jnim/java/lang
# ...
v.setText(cast[CharSequence](String.new("hello flappy nim")))

But it's better to patch jnim and introduce CharSequence along with java.lang.