Kotlin Error: "Unresolved reference: nightMode" in my MainActivity.kt file

443 views Asked by At

I have created a To-Do List App in Android Studio using Kotlin and wish to add an options menu item that toggles between regular theme and night mode theme. I am following this tutorial

I have entered everything into my existing app but get the error "Unresolved reference: night mode" in my MainActivty.kt file. I am also getting errors "Expecting an element" and "Expecting an expression". My version of Android Studio is 4.2.1. I am attaching the code from the MainActivity.kt, main_menu.xml, and strings.xml.

MainActivity.kt

 override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        intent nightMode = AppCompatDelegate.getDefaultNightMode()
        if (nightMode == AppCompatDelegate.MODE_NIGHT_YES){
            menu?.findItem(R.id.night_mode)?.setTitle(R.string.day_mode)
        } else{
            menu?.findItem(R.id.night_mode)?.setTitle(R.string.night_mode)
        }
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if(item.itemId ==R.id.night_mode){
            intent nightMode = AppCompatDelegate.getDefaultNightMode()
            if (nightMode == AppCompatDelegate.MODE_NIGHT_YES) {
                AppCompatDelegate.setDefaultNightMode(
                    AppCompatDelegate.MODE_NIGHT_NO)
            } else {
                AppCompatDelegate.setDefaultNightMode(
                    AppCompatDelegate.MODE_NIGHT_YES)
            }
        }
        recreate()
            return true
    }

main_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/night_mode"
        android:title="@string/night_mode>"/>

</menu>

strings.xml

<resources>
    <string name="app_name">To do List</string>
    <string name="night_mode">Night Mode</string>
    <string name="day_mode">Day Mode</string>
</resources>
1

There are 1 answers

2
laalto On

intent nightMode is not a valid expression.

The original tutorial Java code seems to have int nightMode there, declaring a variable of type int (as in integer).

In kotlin you can declare a variable with val (immutable) or var (mutable).

So, change the intent to val.