Kotlin Android TextView KotlinNullPointerException - android

I decided to write small program in Kotlin. And now I have one problem which I can't fix. This is due to NullPointerException. And the Logcat always shows me an error in line where I wrote this textView_msg!!.text = "${currencyList[p2]}". Please help me.
This is my code
open class CurrencyActivity : AppCompatActivity() {
open var textView_msg: TextView? = null
open var textView: TextView? = null
open val currencyList = arrayOf("AUD","CAD","CHF","EUR","GBP","JPY","NZD","KHR","USD","CNY","THB","INR")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.currency_activty)
setUpSpinnerData()
}
//This method will be invoked to setup data of the spinner views
//to show lists of currency types for selection
fun setUpSpinnerData() {
textView_msg = findViewById(R.id.setCurrencyFrom) as TextView
textView = findViewById(R.id.setCurrencyTo) as TextView
val spFrom: Spinner = findViewById(R.id.fromCurrency)
spFrom.onItemSelectedListener = ItemSelectedFrom()
val afrom: ArrayAdapter<String> = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, currencyList)
spFrom.adapter = afrom
val spTo: Spinner = findViewById(R.id.toCurrency)
spTo.onItemSelectedListener = ItemSelectedTo()
val ato: ArrayAdapter<String> = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, currencyList)
spTo.adapter = ato
}
class ItemSelectedFrom: CurrencyActivity(), AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
//textView_msg = findViewById(R.id.setCurrencyFrom) as TextView
textView_msg!!.text = "${currencyList[p2]}"
}
}
class ItemSelectedTo : CurrencyActivity(), AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
//textView = findViewById(R.id.setCurrencyTo) as TextView
textView!!.text = "${currencyList[p2]}"
}
}
}`

Yes, I did it. Thanks everybody who tried to help me. I just a little bit rewrite it(but in comments I have an old code). This is my solution.
class CurrencyActivity : AppCompatActivity() {
var textView_msg: TextView ?= null
var textView: TextView ?= null
var currencyList = arrayOf("AUD","CAD","CHF","EUR","GBP","JPY","NZD","KHR","USD","CNY","THB","INR")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.currency_activty)
setUpSpinnerData()
}
//This method will be invoked to setup data of the spinner views
//to show lists of currency types for selection
fun setUpSpinnerData() {
val spFrom: Spinner = findViewById(R.id.fromCurrency)
spFrom.onItemSelectedListener = onItemSelectedListener0
val afrom: ArrayAdapter<String> = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, currencyList)
spFrom.adapter = afrom
val spTo: Spinner = findViewById(R.id.toCurrency)
spTo.onItemSelectedListener = onItemSelectedListener1
val ato: ArrayAdapter<String> = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, currencyList)
spTo.adapter = ato
}
var onItemSelectedListener0: OnItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
textView_msg = findViewById(R.id.LALALALA)
Log.e("KUKU", currencyList[position])
textView_msg?.text = "${currencyList[position]}"
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
var onItemSelectedListener1: OnItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
textView = findViewById(R.id.NANANANA)
textView?.text = "${currencyList[position]}"
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
// class ItemSelectedFrom: CurrencyActivity(), AdapterView.OnItemSelectedListener {
// override fun onNothingSelected(p0: AdapterView<*>?) {}
//
// override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
// textView_msg = findViewById(R.id.LALALALA)
// Log.e("KUKU", currencyList[position])
// textView_msg?.text = "${currencyList[position]}"
// }
// }
//
// class ItemSelectedTo : CurrencyActivity(), AdapterView.OnItemSelectedListener {
// override fun onNothingSelected(p0: AdapterView<*>?) {}
//
// override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
// textView = findViewById(R.id.NANANANA)
// textView?.text = "${currencyList[position]}"
// }
// }
}
And now what was the problem. Explaining.
var textView_msg: TextView ?= null
// Initialize it somewhere.
textView_msg?.text = "${currencyList[position]}" // Calls setText if textView_msg != null
textView_msg!!.text = "${currencyList[position]}" // Throws an exception if textView_msg == null

Related

How to retrieve the String of a selected item in spinner outside of onItemSelected method?

I need to retrieve the selected string in a spinner outside of the .onItemSelectedListener.
The dropdown menu contains "Each week, each month, each year" strings and I need to retrieve that selected item String in order use them in if conditionals outside of the function.
I've only seen people making Toasts in the onItemSelected function but this doesn't solve my problem.
This is my code:
val spinner = binding.tvAutoComplete
val powtarzanie = resources.getStringArray(R.array.powtarzanie)
val arrayAdapter = ArrayAdapter(requireContext(),
R.layout.dropdown_powtarzaj_item,
powtarzanie)
spinner.setAdapter(arrayAdapter)
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
val itemText: String = parent?.getItemAtPosition(position).toString()
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("Not yet implemented")
}
}
One way and probably the most simple way to go about this is to define a global variable:
private var spinnerSelection: String? = null
and just change it in your onItemSelected implementation:
spinnerSelection = parent?.getItemAtPosition(pos).toString()
Example code showing the whole flow:
class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {
private var spinnerSelection: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val spinner: Spinner = findViewById(R.id.spinner)
spinner.onItemSelectedListener = this
ArrayAdapter.createFromResource(
this,
R.array.numbers_array,
android.R.layout.simple_spinner_item
).also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
}
val button: Button = findViewById(R.id.button)
button.setOnClickListener {
Log.d("MainActivity", "Currently selected item: $spinnerSelection")
}
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, pos: Int, id: Long) {
spinnerSelection = parent?.getItemAtPosition(pos).toString()
}
override fun onNothingSelected(parent: AdapterView<*>?) {
//TODO("Not yet implemented")
}
}

spinner in kotlin not populating

my spinner is not populating
#RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val adapter = ArrayAdapter.createFromResource(requireContext(), R.array.duration, android.R.layout.simple_spinner_item) as SpinnerAdapter
_binding?.duration?.adapter = adapter
_binding?.duration?.onItemSelectedListener = object :
AdapterView.OnItemSelectedListener {
#RequiresApi(Build.VERSION_CODES.O)
override fun onItemSelected(parent: AdapterView<*>,
view: View, position: Int, id: Long) {
val followeredata = followerData()
var followercount = followeredata.getcount(position)
Log.i("menu selected"," on item is selected")
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("Not yet implemented")
}
}
}
I have tried different methods of creating adapter but none of them are able to populate the spinner. but if I create them from XML:entries it works fine. how do I populate my spinner from code

I can't use the spinner function properly[kotlin]

I'm having trouble using the sendCommand function when the user change the spinner item to "Red":
class SetTrainingRouteActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_set_training_route)
val spinner: Spinner = findViewById(R.id.S24)
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter.createFromResource(
this,
R.array.A24,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
spinner.adapter = adapter
}
S24.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (S24.equals("Red")) {
sendCommand("1000024")
}
}
}
}
private fun sendCommand(input: String) {
if (ControlActivity.arduino_bluetoothSocket != null) {
try{
ControlActivity.arduino_bluetoothSocket!!.outputStream.write(input.toByteArray())
} catch(e: IOException) {
e.printStackTrace()
}
}
}
}
<string-array name="A24">
<item>Off</item>
<item>Red</item>
<item>Green</item>
<item>Blue</item>
</string-array>
<Spinner
android:id="#+id/S24"
android:textColor="#color/text_matrix_cell"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:entries="#array/A24" />
You are reading value in a wrong way. Below code will work
S24.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val selectedItem = parent?.getItemAtPosition(position)
if (selectedItem?.equals("Red") == true) {
sendCommand("1000024")
}
}
}
What you are doing is comparing spinner instance to value "Red" which will never work, because they are not same.
You need to read the value using correct method and then compare them.

android kotlin spinner working for API 23, but not working for API 21

I test my spinner in real device SM-G900F API 23, it is working well. But it is not working in SM-N9005 API 21. It shows the spinner but it did not show any options when I click the spinner.
Please see my code below and help to solve this issue.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_country_selector)
val spinnerOne = search_spinner1
val spinnerTwo = search_spinner2
val userDetail = UserDetail(this)
//SpinnerOne
spinnerOne.adapter = ArrayAdapter<String>(this, R.layout.item, countryArray)
//SpinnerTwo
val dataAdapter = ArrayAdapter<String>(this, R.layout.item, tempArray)
spinnerTwo.setAdapter(dataAdapter)
spinnerOne.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
countrySelected = parent?.getItemAtPosition(position).toString()
citySelected = countrySelected
if (countrySelected == "香港") {
userDetail.saveCountry(countrySelected)
userDetail.saveCity(countrySelected)
spinnerTwo.visibility = View.GONE
finish()
} else if (countrySelected == "澳門") {
userDetail.saveCountry(countrySelected)
userDetail.saveCity(countrySelected)
spinnerTwo.visibility = View.GONE
finish()
} else if (countrySelected == "台灣") {
userDetail.saveCountry(countrySelected)
tempArray.clear()
tempArray.addAll(taiwanArray)
dataAdapter.notifyDataSetChanged()
spinnerTwo.visibility = View.VISIBLE
}
}
}
//hide spinner2
spinnerTwo.visibility = View.GONE
spinnerTwo.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
citySelected = parent?.getItemAtPosition(position).toString()
if (citySelected == "選擇城市") {
} else {
userDetail.saveCity(citySelected)
finish()
}
}
}
Here with the xml file:
enter code here
I found the answer
android:spinnerMode="dialog"
add this code it will be work for API 21 and 23

Android Kotlin onItemSelectedListener for spinner not working

I have a spinner with some items (strings).
I want to add the selected items to a list. I read online that I should use the onItemSelectedListenerrather than the onItemClickListener.
I implemented this but I don't know how to complete the step of adding it to the list.
class NewKitListActivity : AppCompatActivity() {
var spinnerArray = arrayOf("Dumbell", "Punching Bag", "Yoga Ball", "Skipping Rope")
//var spinnerArray = arrayOf(DataService.kitList)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new_kit_list)
val spinner = newKitItemSpinner
val spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray)
//selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = spinnerArrayAdapter
spinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val selectedItem = parent.getItemAtPosition(position).toString()
if (selectedItem == "Add new category") {
// do your stuff
}
} // to close the onItemSelected
override fun onNothingSelected(parent: AdapterView<*>) {
}
}}}
Thanks
(in Kotlin)Use this code:
yourSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
Thanks this is helpful for me, Its working fine !
daysSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
Add extension function
fun Spinner.selected(action: (position:Int) -> Unit) {
this.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
action(position)
}
}
}
simple use
spinner.selected {
println(it) //selected position
}
string will not be able to check using '==' instead you need to use equals("string")
if (selectedItem.equals("Add new category")) {
// do your stuff
}
I implemented like this.
1. Create Empty Mutable List
2. Set onItemSelectedListner on spinner
3. When user select item add that to mutable list
Check my this answer for more info. It will help you: Android Koltin pass spinner values to mutable list
instead of:
var spinnerArray = arrayOf("Dumbell", "Punching Bag", "Yoga Ball", "Skipping Rope")
try
var spinnerArray = mutableListOf<String>("Dumbell", "Punching Bag", "Yoga Ball", "Skipping Rope")
just had the same situation when I was trying to get a sqlite table´s $_ID and populate the spinner with them
// Extends AdapterView.OnItemSelectedListener
class Dialogs : DialogFragment(), AdapterView.OnItemSelectedListener {}
//Somewhre in onCreate (I'm using databinding but you don't have to)
binding.spinnerDialogEstados.onItemSelectedListener = this
// then implement members...
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
TODO("Not yet implemented")
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("Not yet implemented")
}

Categories

Resources