Search code examples
android-studiokotlinrandomcolorshex

Cannot get random color generator in Kotlin to work


Trying to generate a random color hexadecimal...Here's my code so far

import android.graphics.Color
import kotlin.random.Random
import kotlin.random.nextInt

fun main(){
    val rnd = Random.Default //kotlin.random
    val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
    }

This is the error I'm getting

Exception in thread "main" java.lang.RuntimeException: Stub!
    at android.graphics.Color.argb(Color.java:137)
    at com.example.functionexample.FunctionExampleKt.main(FunctionExample.kt:12)
    at com.example.functionexample.FunctionExampleKt.main(FunctionExample.kt)

Process finished with exit code 1

Tried searching for this error online but can't find anything. Theres no error messages on my actual code but when I run it I get that


Solution

  • Like bylazy says in the comments, you can't use Android libraries outside of an Android device like that. You're getting the "Stub!" error because the library you have downloaded doesn't have any code in its methods, except to throw an exception with that message. They're just placeholders - but when you run it on a device/emulator, the full library will be available there with actual method implementations.

    If you just need to create a hex string, you can call toString(16) on your random numbers to get the individual hex parts. You could create a function like this:

    fun getRandomHex() = Random.nextInt(255).toString(16).uppercase()
    
    println("FF${getRandomHex()}${getRandomHex()}${getRandomHex()}")
    

    Or maybe use a property

    val rndHex get() = Random.nextInt(255).toString(16).uppercase()
    
    println("FF$rndHex$rndHex$rndHex")