Home > Enterprise >  Android Studio Kotlin app "keeps stopping" when I run it
Android Studio Kotlin app "keeps stopping" when I run it

Time:05-16

I am just trying to set up a spinner configured as a dropdown menu, but I can't even test my app to see if it works because every time I run it, it immediately crashes. I know that my issue is related to a null object reference at line 21 in my MainActivity.kt file. Here is the problem code: val spinner: Spinner = findViewById<Spinner>(R.id.locations) The id of the spinner is locations, so I'm not sure why this is coming back as a null value. Here is also the full code for the file:


import android.app.Activity
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Spinner
import android.widget.ArrayAdapter
import android.widget.AdapterView

private var userLocation: Any = ""
private var userDestination: Any = ""


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    val spinner: Spinner = findViewById<Spinner>(R.id.locations)
    val locationsAdapter: ArrayAdapter<CharSequence> = ArrayAdapter.createFromResource(
        this,
        R.array.rooms,
        android.R.layout.simple_spinner_item
    ).also { adapter ->
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinner.adapter = adapter
    }
}

class SpinnerActivity : Activity(), AdapterView.OnItemSelectedListener {
    override fun onItemSelected(parent: AdapterView<*>, view: View?, pos: Int, id:Long) {
        userLocation = parent.getItemAtPosition(pos)
        val spinner: Spinner = findViewById(R.id.locations)
        spinner.onItemSelectedListener = this
    }
    override fun onNothingSelected(parent: AdapterView<*>) = Unit
}

CodePudding user response:

Declare spinner global for MainActivity:

private lateinit var spinner: Spinner

On the method onCreate initialise the spinner and set its adapter, I would recommend you to set the array adapter as follows:

spinner = findViewById<Spinner>(R.id.locations)

spinner.adapter = ArrayAdapter(this, R.layout.drop_down_generic_item, resources.getStringArray(R.array.rooms))

I don't really understand the SpinnerActivity you showed in the question, sorry. But in MainActivity you can set the spinner.onItemSelectedLister() as follows:

spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, position: Int, p3: Long) {
                val selectedRoom = adapterView?.getItemAtPosition(position)
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {
                
            }
}

I don't want to confuse you, but have a look at a TextInputLayout with an AutoCompleteTextView, just as a hint. :D

  • Related