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
Related
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")
}
}
I have a problem with the spinner inside a fragment. The spinner is filled with data, but when I select an item I don't see logs, and in the spinner, it does not select elements. When I used nearly the same code as an activity it worked (Just changed the context to this in the adapter)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_edit_stoper, container, false)
val tagSpinner = view.findViewById<Spinner>(R.id.editSpinner)
val items: MutableList<String> = ArrayList("a","b","c")
tagSpinner.adapter = ArrayAdapter(this.requireActivity(), android.R.layout.simple_spinner_item, items) as SpinnerAdapter
tagSpinner.onItemSelectedListener = this
return view
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Log.d(TAG,"OnItemSelected: $type")
}
override fun onNothingSelected(parent: AdapterView<*>?) {
Log.d(TAG,"error")
}
}
Is your fragment really a listener for spinner?
Write a custom listener and use that instead of your fragment.
inner class SpinnerStateChangeListener : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
// do sth here
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// do sth here
}
}
Now you can set your listener like this:
tagSpinner.onItemSelectedListener = SpinnerStateChangeListener()
Try moving your implementation from Fragment directly to spinner. remove override from class and instead of
tagSpinner.onItemSelectedListener = this
do
tagSpinner.onItemSelectedListener = object :AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
Log.d(TAG,"error")
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Log.d(TAG,"OnItemSelected: $type")
}
}
The solution is to add requireActivity().applicationContext in the adapter to change the activityFragment to a context:
...
val items: MutableList<String> = ArrayList("a","b","c")
tagSpinner.adapter = ArrayAdapter(requireActivity().applicationContext, android.R.layout.simple_spinner_item, items) as SpinnerAdapter
tagSpinner.onItemSelectedListener = this
...
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.
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
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")
}