MaR_11
MaR_11

Reputation: 11

Kotlin - I get error beacuse id is null. How to fix it?

I'm trying to make a program which will display color that you choose. So you would slide on picture with color shades and application would display you current color. Under that there is text view that will display RGB value of current color. But when I tried to write code for color picker I get this error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.leds/com.example.leds.MainActivity}:
java.lang.NullPointerException: color_picker must not be null

I tried everything but i can't fix it.

My kotlin code:

class MainActivity : AppCompatActivity() {

private lateinit var bitmap:Bitmap

@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    color_picker.isDrawingCacheEnabled = true
    color_picker.buildDrawingCache(true)

    val wheel = findViewById<ImageView>(R.id.color_picker)

    wheel.setOnTouchListener { v, event ->
        if (event.action == MotionEvent.ACTION_DOWN || event.action == MotionEvent.ACTION_MOVE) {
            bitmap = color_picker.drawingCache

            val pixel = bitmap.getPixel(event.x.toInt(), event.y.toInt())

            val r = Color.red(pixel)
            val g = Color.green(pixel)
            val b = Color.blue(pixel)

            selected_color_view.setBackgroundColor(Color.rgb(r,g,b))

            color_value.text = "RGB: $r, $g, $b"
        }
        true}

And my xml code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">

<ImageView
    android:id="@+id/color_picker"
    android:layout_width="350dp"
    android:layout_height="450dp"
    android:src="@drawable/colour_wheel"/>

<View
    android:id="@+id/selected_color_view"
    android:layout_width="100dp"
    android:layout_height="100dp" />

<TextView
    android:id="@+id/color_value"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="RGB:"
    android:textColor="#000"
    android:textSize="18sp"/>

Upvotes: 1

Views: 160

Answers (1)

qki
qki

Reputation: 1929

It's because you did not initialize variable color_picker before using it

color_picker.isDrawingCacheEnabled = true
color_picker.buildDrawingCache(true)

You have to initialize it like you did in val wheel = findViewById<ImageView>(R.id.color_picker) and then you can modify it like wheel.isDrawingCacheEnabled = true

@EDIT You have to initialize variable wheel first, then you can call it's properties.

val wheel = findViewById<ImageView>(R.id.color_picker)
wheel.isDrawingCacheEnabled = true
wheel.buildDrawingCache(true)

Upvotes: 1

Related Questions