Posts

Showing posts with the label kotlin

What does it mean that Kotlin based apps will get a performance boost on Android P

Image
Clash Royale CLAN TAG #URR8PPP What does it mean that Kotlin based apps will get a performance boost on Android P Over the last few of months in a bunch of places I've seen the information that Android P will give the performance boost to Kotlin based apps (e.g. here and here). On the official Android blog, Dave Burke in "Previewing Android P" post described it in a few words: Kotlin is a first-class language on Android, and if you haven't tried it yet, you should! We've made an enduring commitment to Kotlin in Android and continue to expand support including optimizing the performance of Kotlin code. In P you'll see the first results of this work -- we've improved several compiler optimizations, especially those that target loops, to extract better performance. We're also continuing to work in partnership with JetBrains to optimize Kotlin's generated code. You can get all of the latest Kotlin performance improvements just by keeping Android Studio...

Spring Boot include ID field in json

Image
Clash Royale CLAN TAG #URR8PPP Spring Boot include ID field in json Propably it's very simple but everything what I found is related to Spring Data Rest. I'm using "spring-boot-starter-web" and I can't found any solution... Here is my entity clas: @Entity @Table(name = "buses") class Bus( @Id @JsonProperty("sideNumber") @JsonInclude private val sideNumber: Int, @NotBlank var longitude: Double, @NotBlank var latitude: Double ) I tried to annotate sideNumber(Id) property with @JsonInclude and @Jsonproperty but with no luck. In my json reponse I only get longitude and latitude... My controller looks like that. @RestController @RequestMapping("/api") class BusController { @Autowired private lateinit var busRepository: BusRepository @GetMapping("/buses") fun getAllBuses(): List<Bus> { return busRepository.findAll() } @PostMapping("/buses") fun cre...

Re-use @ApiResponses error responses in the code

Image
Clash Royale CLAN TAG #URR8PPP Re-use @ApiResponses error responses in the code I use swagger with kotlin and have the code: @MyApiGroup1 @RestController interface MyController1 { @ApiResponses( ApiResponse(code = 200, message = "OK", response = SomeEntity::class), ApiResponse(code = 400, message = "My error 1", response = MyError::class), ApiResponse(code = 400, message = "My error 2", response = MyError::class), ApiResponse(code = 409, message = "My error 3", response = MyError::class) ) @RequestMapping("/", method = arrayOf(RequestMethod.GET)) fun getMyGet(param: Params): ResponseEntity<SomeEntity> { //some magic } @ApiResponses( ApiResponse(code = 201, message = "ADD"), ApiResponse(code = 400, message = "My error 1", response = MyError::class), ApiResponse(code = 400, message = "My error 2", response = MyError::cla...

How can I make this singleton simpler in Kotlin?

Image
Clash Royale CLAN TAG #URR8PPP How can I make this singleton simpler in Kotlin? How can I make this singleton simpler in Kotlin for the Android room database initialization? @Database(entities = arrayOf(Book::class, User::class), version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun bookModel() : BookDao abstract fun userModel() : UserDao companion object { private var INSTANCE: AppDatabase? = null fun getInMemoryDatabase(context: Context): AppDatabase { if (INSTANCE == null) { INSTANCE = Room.inMemoryDatabaseBuilder(context.applicationContext, AppDatabase::class.java).build() } return INSTANCE!! } fun destroyInstance() { INSTANCE = null } } } I had the same issue few days ago. – Abner Escócio 13 hours ago ...

My Android application crashes when switch to multi window mode

Image
Clash Royale CLAN TAG #URR8PPP My Android application crashes when switch to multi window mode My Android application crashes when switch to multi window mode. When this application is only displayed on screen and I long click multitask button, this application crashes. In contrast, standard launch from home launcher, this problem does not appear. This is stacktrace. java.lang.RuntimeException: Unable to start activity ComponentInfo{com.otk1fd.simplemio/com.otk1fd.simplemio.activities.MainActivity}: android.view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class fragment at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4699) at android.app.ActivityThread.-wrap18(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1595)...

How to create Location object

Image
Clash Royale CLAN TAG #URR8PPP How to create Location object I am trying to make a new location and set its latitude/longitude like this: var targetlocation = Location("") //this example code doesn't work below targetlocation.setLatitude(55.555555) targetlocation.setLongitude(55.555555) How can I do this correctly in kotlin? Thanks. 1 Answer 1 I haven't tried this but try doing this. var targetlocation = Location("") targetlocation.latitude = 55.555555 targetlocation.longitude = 55.555555 Hi I tried that already but i get "expecting member declaration" error – Noob 4 mins ago By clicking "Post Your Answer", you acknowledge that you have read our updated terms of s...

Is it possible to implement the spread operator on other classes?

Image
Clash Royale CLAN TAG #URR8PPP Is it possible to implement the spread operator on other classes? Is it possible to implement the spread operator on other classes in the same way you can with other operators like + , for example: + class Demo{ operator fun plus(i:Int):Demo { ... } } Do you mean the one we use for varargs? Operator overloading is documented here: kotlinlang.org/docs/reference/operator-overloading.html. – JB Nizet 6 mins ago By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Class not found, Empty test suite in androidTest using Android Studio 3.0.1, Room, Kotlin

Image
Clash Royale CLAN TAG #URR8PPP Class not found, Empty test suite in androidTest using Android Studio 3.0.1, Room, Kotlin I have a problem with running my androidTest. Here is my setup in gradle: apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { compileSdkVersion 26 defaultConfig { applicationId "com.blabla.shoppinglistapp" minSdkVersion 17 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } ext.daggerVersion = '2.11' ext.roomVersion = '1.0.0' ext.mockitoVersion = '2.11.0' dependencies { implementation fileTree(dir: 'libs', in...

How to implement Multi Dex in Instant Apps?

Image
Clash Royale CLAN TAG #URR8PPP How to implement Multi Dex in Instant Apps? I am making an instant app. I have the base feature and the installed module . The two gradle files can't have a defaultConfig{} , so that is why I have set multiDex true only in the installed build.gradle file. Running the instant app though throws a compile error as there is no multiDex anywhere. base feature installed module defaultConfig{} multiDex true build.gradle multiDex Any ideas? Thanks. 1 Answer 1 The Solution lies within making two flavours in base.gradle : base.gradle flavorDimensions 'delivery' productFlavors { instant { dimension 'delivery' minSdkVersion rootProject.minSdkInstant multiDexEnabled true } installed { dimension 'delivery' } } Note: you still have to add multiDexEnabled true in installed.gradle 's defaultConfig{} Al...

What value will return when I opearte transform?.invoke() if transform is null in Kotlin?

Image
Clash Royale CLAN TAG #URR8PPP What value will return when I opearte transform?.invoke() if transform is null in Kotlin? I was told that invoke() can be operated safely. invoke() 1: What value will return when I operate transform?.invoke() in Code A? I think the Code val str = transform?.invoke(element) ?: element.toString() is equivalent to the following code, right? transform?.invoke() val str = transform?.invoke(element) ?: element.toString() val temp= transform?.invoke(element) val str=temp?: element.toString() 2: I don't know whether .let is another choice in Code B, could you tell me? .let Code A fun <T> Collection<T>.joinToString( separator: String = ", ", prefix: String = "", postfix: String = "", transform: ((T) -> String)? = null ): String { val result = StringBuilder(prefix) for ((index, element) in this.withIndex()) { if (index > 0) result.append(separator) ...

Having a button appear when a Text Input field is not empty (Kotlin in Android)

Image
Clash Royale CLAN TAG #URR8PPP Having a button appear when a Text Input field is not empty (Kotlin in Android) I am trying to enable a button on entering text in an input field. Something similar to this: Enable a button on entering text in input field ...but in Kotlin. My current code looks like : override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) listOf(textInput1, textInput2, textInput3).map { it.setOnEditorActionListener() { v, _, _ -> showButtons(it) true } } } and the function is empty: fun showButtons(textInputHolder: TextInputEditText){ if (textInputHolder == textInput1 || textInput2) { button1.visibility = View.VISIBLE } else { button2.visibility = View.VISIBLE } } Basically, I want to show different buttons depending on which one of the list(textInput1, textInput2, textInput3) is being edited. Thanks, F ...

Why does Kotlin have two types of constructors?

Why does Kotlin have two types of constructors? Kotlin has two types of constructors, primary and secondary. What is the purpose of having two types? In my opinion it makes the code more complicated and inconsistent. If both types of constructors create objects of a class, they are equally important to a class. Meanwhile, multiple initialisers also introduce confusion and reduce readability. 2 Answers 2 Primary constructors cover the poplular use case when you need to save the values passed as the constructor arguments to the properties of the instance. Basically, a primary constructor provides a shorthand for both declaring a property and initializing it from the constructor parameter. Note that you can do the same without primary constructors at all: class Foo { val bar: Bar constructor(barValue: Bar) { bar = barValue } } But, since this happens really often in the codebases, K...

Kotlin graphql dataloader/fetcher example

Kotlin graphql dataloader/fetcher example I am looking at this https://github.com/graphql-java/java-dataloader and wondering if anyone has a complete "hello world" example for using this in Kotlin and springboot app? I am quite new to Kotlin and GraphQL, so any help would really be appreciated. Thanks & regards Tin By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

How can I convet MutableMap to vararg values: Pair?

How can I convet MutableMap<String, Any?> to vararg values: Pair<String, Any?>? The following code is from "Kotlin for Android Developers", you can access it at https://github.com/antoniolg/Kotlin-for-Android-Developers In order to insert a row data into CityForecastTable.NAME , I have to pass a vararg values by Source Code fun SQLiteDatabase.insert CityForecastTable.NAME vararg fun SQLiteDatabase.insert 1: The author make a extension toVarargArray() to convert a MutableMap<String, Any?> to Pair<String, Any?> , I don't know whether there is a better way to do that. Do I need to use a extension function? toVarargArray() MutableMap<String, Any?> Pair<String, Any?> 2: The author have to use the code it.value!! in Code C , I don't know if the code fun <K, V : Any> Map<K, V?>.toVarargArray(): Array<out Pair<K, V?>> = map({ Pair(it.key, it.value) }).toTypedArray() is right? it.value!! fun <K, V : Any...