Posts

Showing posts with the label Kotlin

Can Kotlin Data Class Have More Than One Constructor?

Answer : A Kotlin data class must have a primary constructor that defines at least one member. Other than that, you can add secondary constructors as explained in Classes and Inheritance - Secondary Constructors. For your class, and example secondary constructor: data class User(val name: String, val age: Int) { constructor(name: String): this(name, -1) { ... } } Notice that the secondary constructor must delegate to the primary constructor in its definition. Although many things common to secondary constructors can be solved by having default values for the parameters. In the case above, you could simplify to: data class User(val name: String, val age: Int = -1) If calling these from Java, you should read the Java interop - Java calling Kotlin documentation on how to generate overloads, and maybe sometimes the NoArg Compiler Plugin for other special cases. Yes, but each variable should be initialized, so you may set default arguments in your data class constructo...

Android Architecture Components: Gradle Sync Error For Dependency Version

Answer : As @RedBassett mentions Support libraries depends on this lightweight import (runtime library) as explained at android developers documentation. This is, android.arch.lifecycle:runtime:1.0.0 is spreading up in the dependency tree as a result of an internal api (transitive) import so in my case I only had to include extensions library as "api" instead of "implementation" so that it will override its version to the highest (1.1.1). In conclusion, change implementation "android.arch.lifecycle:extensions:1.1.1" to api "android.arch.lifecycle:extensions:1.1.1" In your main build.gradle file allprojects { ... configurations { all { resolutionStrategy { force "android.arch.lifecycle:runtime:1.1.1" } } } } This will enforce version 1.1.1 Apparently support-v4 was causing the conflict. In the case of this question, the Gradle dependency task wasn...

Access Application Context In Companion Object In Kotlin

Answer : please see this go to link class MainApplication : Application() { init { instance = this } companion object { private var instance: MainApplication? = null fun applicationContext() : Context { return instance!!.applicationContext } } override fun onCreate() { super.onCreate() // initialize for any // Use ApplicationContext. // example: SharedPreferences etc... val context: Context = MainApplication.applicationContext() } } Actually I'm working inside an Android library and the class is abstract, so can't go with the already suggested solutions. However, I found way to do that. Creat a lateinit Context field inside companion object. abstract class MyClass { companion object { private lateinit var context: Context fun setContext(con: Context) { context=con } } } And then set it after the app has s...

Android Vibrate Is Deprecated. How To Use VibrationEffect In Android>= API 26?

Answer : Amplitude is an int value. Its The strength of the vibration. This must be a value between 1 and 255, or DEFAULT_AMPLITUDE which is -1. You can use it as VibrationEffect.DEFAULT_AMPLITUDE More details here with kotlin private fun vibrate(){ val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE)) } else { vibrator.vibrate(200) } } You can use this for haptic feedback (vibration): view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); There are other constants available in HapticFeedbackConstants like VIRTUAL_KEY , KEYBOARD_TAP ...

Accessing Kotlin Extension Functions From Java

Answer : All Kotlin functions declared in a file will be compiled by default to static methods in a class within the same package and with a name derived from the Kotlin source file (First letter capitalized and ".kt" extension replaced with the "Kt" suffix). Methods generated for extension functions will have an additional first parameter with the extension function receiver type. Applying it to the original question, Java compiler will see Kotlin source file with the name example.kt package com.test.extensions public fun MyModel.bar(): Int { /* actual code */ } as if the following Java class was declared package com.test.extensions class ExampleKt { public static int bar(MyModel receiver) { /* actual code */ } } As nothing happens with the extended class from the Java point of view, you can't just use dot-syntax to access such methods. But they are still callable as normal Java static methods: import com.test.extensions.ExampleKt; MyMod...

AsReversed() Vs Reversed() In Kotlin?

Answer : In Kotlin, both reversed and asReversed have their own unique functions. The Reverse function returns a list with elements in reversed: order. Reversed Function Whereas, the asReversed function returns a reversed read-only view of the original List i.e., all changes made in the original list will be reflected in the reversed one. asReversed Function The difference between the two are that once the asReversed() function has been used, any changes in the original list will be reflected in the reversed list as well. But the same doesn't hold valid or true when the reversed() function is being used. It's merely used to reverse a list. Example: val list = mutableListOf(0, 1, 2, 3, 4, 5) val asReversed = list.asReversed() val reversed = list.reversed() println("Original list: $list") println("asReversed: $asReversed") println("reversed: $reversed") list[0] = 10 println("Orig...

Android With Kotlin - How To Use HttpUrlConnection

Answer : Here is a simplification of the question and answer. Why does this fail? val connection = HttpURLConnection() val data = connection.inputStream.bufferedReader().readText() // ... do something with "data" with error: Kotlin: Cannot access '': it is 'protected/ protected and package /' in 'HttpURLConnection' This fails because you are constructing a class that is not intended to directly be constructed. It is meant to be created by a factory, which is in the URL class openConnection() method. This is also not a direct port of the sample Java code in the original question. The most idiomatic way in Kotlin to open this connection and read the contents as a string would be: val connection = URL("http://www.android.com/").openConnection() as HttpURLConnection val data = connection.inputStream.bufferedReader().readText() This form will auto close everything when done reading the text or on an exception. If you...

Android Get Current Timestamp?

Answer : The solution is : Long tsLong = System.currentTimeMillis()/1000; String ts = tsLong.toString(); From developers blog: System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis() , consider listening to the ACTION_TIME_TICK , ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes. 1320917972 is Unix timestamp using number of seconds since 00:00:00 UTC on January 1, 1970. You can use TimeUnit class for unit conversion - from System.currentTimeMillis() to s...