Questions tagged [kotlin]

10173 questions
1

votes
1

answer
800

Views

NotSerializableException when pass kotlin function in bundle on saving instance state

After I pass kotlin function into Bundle in onSaveInstanceState I got NotSerializableException: java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = MyActivity$showFragmentA$1) at android.os.Parcel.writeSerializable(Parcel.java:1447) at android.os.Parcel...
Alexey Nikitin
1

votes
2

answer
499

Views

Can I call Kotlin function from Dart

Using Flutter, a kotlin/swift function can be called by something like: file.dart: static const platform = const MethodChannel('my.test.flutterapp/battery'); final int result = await platform.invokeMethod('getBatteryLevel'); file.kt: private val CHANNEL = 'my.test.flutterapp/battery' MethodChannel(f...
Hasan A Yousef
1

votes
1

answer
1.8k

Views

How do I swagger generate Kotlin?

I'm trying to generate kotlin code from a swagger json file, and I can't figure out the command-line parameters that should be used. I've tried Swagger codegen v2.3.1 and v2.2.3 and both fail for kotlin, kotlin-client, and kotlin-server with the same error. What's the correct switch to generate Kot...
John Kaster
1

votes
1

answer
523

Views

Kotlin - use Array<Double> or DoubleArray

What is the main difference in these two: val array: Array = arrayOf() vs val array: DoubleArray = doubleArrayOf() I know that one is using primitive data type double and the second its object based countrepart Double. Is there any penalty or disadvatnage in using plain DoubleArray? Why I want to...
Martin Perry
1

votes
3

answer
1.1k

Views

Navigating multidimensional arrays with nested for-loops in Kotlin

Quite often I am navigating a two-dimensional image matrix of pixels or a three-dimensional volumetric data set. Typically the underlying data structure is a one-dimensional array of some primitive type like Double or Int. The multi-dimensional nature is navigated through by nested for-loops as il...
J.E.Tkaczyk
1

votes
2

answer
431

Views

unresolved reference: override (onCreate)

why is there an unresolved reference on override at the onCreate method? (Kotlin) // unresolved reference: override override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // MapFragment erstellen und anzeigen startMapFragment() mapFragment.getMapAsync(this) // OnClic...
G. Lukas
1

votes
2

answer
223

Views

RxJava 2 mock Observable doesn't work

I use RxJava 2 Observable to wrap barcode scanner in one of my app. This snippet show how I subscribe to Observable and listen to it's events override fun start() { disposables.addAll(subscribeToBarcodeReader(), loadUser()) } private fun subscribeToBarcodeReader(): Disposable { return barcodeObserva...
1

votes
2

answer
288

Views

Authenticator, incorrect translate Java to Kotlin

I'm trying to convert a lot of code Java into Kotlin. I found on stack how to set authentication with OkHttp: client.authenticator(new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { if (responseCount(response) >= 3) { return null; // I...
companyn
0

votes
0

answer
7

Views

How should I set the language en to get only english results from the PlacesClient by Google in Android?

Here are the coordinates I am passing into the emulator: Latitude: 25.0783 Longitude: 55.172 Its not giving me the desired results. Below are the results returned: Dubai AE-DU AE - دبي - United Arab Emirates دبي - الإمارات العربية المتحدة دبي - الإمارات الع...
Sachin Rupani
0

votes
0

answer
6

Views

onEditorActionListener is not working in kotlin

keyboard ime action Done is not working when applied in kotlin language companyCodeTv.setOnEditorActionListener { v, actionId, event -> if (actionId == EditorInfo.IME_ACTION_DONE || event?.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER){ validateFields() true } else false...
anu saini
1

votes
1

answer
330

Views

Error upgrading to Kotlin 1.2.60, Android Studio 3.1.3

Pretext: I have 3 build variants for my project apart from release and debug I also have the staging variant. Gradle sync works completely fine with version 1.2.51, but as soon as I upgrade to version 1.2.60, which released recently, gradle sync fails with the following error message: Could not fi...
MadScientist
1

votes
2

answer
68

Views

In ARCore, how to make node/anchor stick to camera?

I am trying to get an object to stick to camera and follow its movement/rotation. The idea is for a 'fishing game' and i need the rod to be glued to the camera. Is there a way to do this?
Oojiitee
1

votes
1

answer
385

Views

Room database loses data

I'm working on an Android project with Kotlin language and I'm using Room database from android architecture components. These are all my Room database stuff. I'm trying to let the user save information about a book and it works fine while I'm in the app, but when I restart the app, everything has b...
Soroush
1

votes
1

answer
823

Views

What is Cognitive Complexity in sonar report?

Now a days i switched to sonar reports for static code review and performance improvement. Under the rules section I found that the cognitive complexity of my methods are high. You can find cognitive complexity error in sonar as: Go to Project->Issues Tab->Rules Drop-down->Cognitive Complexity Below...
Akshay Paliwal
1

votes
1

answer
241

Views

Kotlin code stack trace shows Java line numbers

I'm trying to debug a couple of crashes for my app in the Google Play Store, but the stack traces showing in the Play Store show Java filenames and line numbers instead of direct references to my Kotlin code. I viewed the Java code in Android Studio, but the line numbers do not match. To view the Ja...
Crag
1

votes
5

answer
299

Views

Sorting Strings that contains number in kotlin

I wanna sort some strings that contain numbers but after a sort, it becomes like this ['s1', 's10', 's11', ... ,'s2', 's21', 's22']. after i search i fount this question with same problem. but in my example, I have mutableList, and I must put all string in myModel.title for example into a mutable li...
Mehrdad Dolatkhah
1

votes
1

answer
173

Views

error: cannot find symbol import com.gourav.news.databinding.ActivityDetailBindingImpl;

I tried Buiding the app but keep getting /Users/gouravkarwasara/Desktop/News2/app/build/generated/source/kapt/debug/com/gourav/news/DataBinderMapperImpl.java:9: error: cannot find symbol import com.gourav.news.databinding.ActivityDetailBindingImpl; ^ symbol: class ActivityDetailBindingImpl locatio...
Gourav karwasara
1

votes
1

answer
96

Views

How to return boolean value from a function in Kotlin

I am new to kotlin. I am reading a key and value from properties file, in a kotlin program. But I don't know how to directly return the value of a key. Please find the application.yml and abc.class(this is a kotlin class) below. application.yml abcconfig: isabcEnabled: default: false xyz: true def:...
umesh
1

votes
1

answer
25

Views

init block in Kotlin with 2+ constructors

Found that init {} block is executed before secondary constructor. So basically i have two constructors (primary and secondary). Primary is used just for initializing simple view. Secondary - trying to populate editViews with data. After secondary constructor im expecting that init block will be exe...
1

votes
1

answer
69

Views

Android MVVM - Update ViewModel when data changes

I'm working on an app using the MVVM pattern with RxJava. The architecture is the following: It's the first time i use this pattern and i'm not sure about the best way to update a ViewModel (and consequently the corresponding View) when a change occurs in the data, made by another component of the a...
Cilla
1

votes
2

answer
84

Views

How to use Generics or Reflection to show/hide fragments? Kotlin Android

I have a fragment manager to show/hide fragments in my app. Right now when I want to show a fragment from any activity or fragment I call this method from the manager fun show(manager: FragmentManager, fragmentTag: String, container: Int, data: Any?): Companion { var fragment = manager.findFragment...
Pablo R.
1

votes
2

answer
75

Views

How do I correctly launch Kotlin coroutines to implement a Caffeine AsyncLoadingCache?

I have a Kotlin JVM server application using coroutines and I need to put a cache in front of a non-blocking network call. I figure I can use a Caffeine AsyncLoadingCache to get the non-blocking cache behaviour I need. The AsyncCacheLoader interface I would need to implement uses CompletableFuture....
Sam
1

votes
1

answer
48

Views

AndroidThreeTen not working in unit test without robolectric?

I'm having trouble creating a unit test without needing robolectric. I am using AndroidThreeTen.init(this) in my code and when I run my test if I disable robolectric I get an error: org.threeten.bp.zone.ZoneRulesException: No time-zone data files registered and if I leave it enabled I get this: [Ro...
Crash1hd
1

votes
3

answer
60

Views

Where to write functions in Kotlin that will be used from other activities in Android?

Here's my MainActivity: MainActivity.kt class MainActivity : AppCompatActivity() { ... } fun becomeClickable(v: Button){ v.alpha = 1f v.isClickable = true } I would like to use becomeClickable() in other activities. What is the best practice for doing that? I previously had becomeClickable() as a...
Zorgan
1

votes
1

answer
21

Views

How to change text size from OnCreate using code in Kotlin

I have an activity which have Spinner and TextView. I want to use the Spinner to change the text size in TextView. there is three size in spinner(small, mediam and large) I put these size in dimen.xml .. how can I use Spinner to Change size? I tried this code but it didn't work val fontSize = arrayO...
Mohamed Wessam
1

votes
2

answer
38

Views

Converting the result of NumberFormat.parse() into a BigDecimal

I've defined a formatter like so: >>> import java.text.NumberFormat >>> val formatter = NumberFormat.getInstance() It would appear that the result of formatter.parse('1,000') is a Long: >>> formatter.parse('1,000')::class class kotlin.Long However, if I try to pass it to the constructor of BigDecima...
Kurt Peek
1

votes
1

answer
26

Views

Gradle generate sources.jar for only public interfaces

I am working on a closed-source Android library (published as an AAR), and want to include some javadocs for consumers, which requires a sources.jar. I know I could cherry-pick each file using an includes property or maybe even a whole package/folder. task('androidSourcesJar', type: Jar) { classifie...
MikeB
1

votes
2

answer
51

Views

Singleton usage creates memory leak in kotlin

Trying to use Singleton class in another Singleton, but somehow it gives me memory leaks. How could i improve it? Here is my example singleton implementation class FirstSingletonClass(val context: Context) { companion object { @Volatile private var instance: FirstSingletonClass? = null fun getInst...
1

votes
1

answer
80

Views

How to pass bytes from Swift (iOS) to Kotlin common module?

To share a implementation of a protocol between an android and iOS app I am experimenting with Kotlin Multiplatform. I set up a basic multiplatform project as described here. It defines common code in the shared module ... fun createApplicationScreenMessage() : String { return 'Kotlin Rocks on ${pla...
Sven
1

votes
1

answer
26

Views

How to close the soft keyboard from a fragment using Kotlin?

I would like to close the soft keyboard from inside a fragment. I am finding a lot of answers but they are all in Java. Usually I am able to transition it to Kotlin quite easily but I am having a hard time with this one. The closest I got was this: fun closeKeyboard() { val activity = activity as Fe...
Tsabary
1

votes
1

answer
62

Views

How to parse retrofit json body using gson in kotlin

I am working on android app writing in kotlin. I have a issue with json parsing actually i am hitting webservice using retrofit library for pojo i have taken kotlin data class. I am getting success response after that i am trying to parse json response with gson library here i am getting error. code...
skyshine
1

votes
2

answer
28

Views

Kotlin generic factory dynamic cast

I want to create factory of objects with generic parameter: interface Foo { fun buzz(param: T) } I have two implementations for tests: class FooImpl1 : Foo { override fun buzz(param: String) { // implementation 1 } } class FooImpl2 : Foo { override fun buzz(param: Int) { // implementation 2 } } Now...
Lau
1

votes
1

answer
21

Views

Not enough information to infer parameter T

Context: I am building a REST API with kotlin using Spring Problem: I have a Kotlin class called Response that accepts a generic like this: class Response { var data: T? = null var dataArray: List? = null var errors: List? = null get() { if (field == null) { this.errors = ArrayList() } return field...
José Nobre
1

votes
2

answer
63

Views

How to reference implementation callback inside “run” or “apply” in Kotlin

How to have the implementation reference inside a 'run' or 'apply' class MyClass : MyCallback { ... fun myMethod() { val myObject = MyObject() myObject.run { setCallback(this) //
1

votes
3

answer
72

Views

How to fix this unchecked cast error when using generics?

In my class I have a list containing TopicNodes. The nodes of those list should extend from the Message class. In the method findNode within the list of nodes there is searched for a node with a specific topic and if it matches it is being returned. The Java compiler complains about the TopicNode be...
Klyner
0

votes
0

answer
8

Views

How to add Java annotations to jni swig API

We are using SWIG to create the JNI API between C++ API to Java in Android. So for example lets say that our C++ class is: class TestAnnotation { public: void setMessage(char * message); char * getMessage(); private: char* message = nullptr; }; SWIG produces this auto generated Java class: public c...
0

votes
0

answer
19

Views

RecyclerView with NonScrollingGridLayoutManager becomes laggy on drag and drop

I am trying to achieve a Grid in recyclerview using NonScrollingGridLayoutManager and for callback i m using ItemTouchHelperCallback so that i can drag and drop items in any position within the grid. It works fine but then later becomes laggy and cause the UI to stuck. Any leads will be of great hel...
Pradeep Singh
0

votes
0

answer
9

Views

Why do I get UnknownPluginException when trying to use a custom Kotlin complier plugin in Gradle?

I have created a custom Kotlin compiler plugin for Gradle. It was inspired by kotlin-allopen (2) and sample-kotlin-compilier-plugin, and is supposed to make all Kotlin classes non-final. The problem is, I'm unable to use it in my projects, I only get the following: Caused by: org.gradle.api.plugins...
neu242
0

votes
0

answer
6

Views

Dagger Injection obtain Dagger/MissingBinding error

When I try to compile the app throw error. [Dagger/MissingBinding] [dagger.android.AndroidInjector.inject(T)] java.util.Map,javax.inject.Provider> cannot be provided without an @Provides-annotated method. public abstract interface AppApplicationComponent extends dagger.android.AndroidInjector { AppA...
jordiz
0

votes
1

answer
14

Views

Recycler view is not update when using carrousel manager library

I'm trying to pull image data into Recycler view (each sub item is a PagerSnapHelper element) but faced below problem 1 - recycler view is not getting update when first time load, sub elements seems to be misalignment. 2 - i have to slide or touch the screen to reload the view, all elements is show...
phong lê

View additional questions