I can't seem to get my driver to update through my app. I have tried but with no luck. I have a possible solution but don't know what the adapter is that needs to be used. This data all happens in my MainActivity. When the new spinner item is selected. I pass the driver through to do new calculations with the correct DRIVER data.
My spinner class:
private fun Spinner( tripsheetlist: ArrayList<DataModel>): String {
var driverlist = tripsheetlist.distinctBy { it.DRIVER }
var driver : String = driverlist[1].DRIVER //this will be the default first picked driver
spnDriver.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
driver = driverlist[p2].DRIVER.toString()
Toast.makeText(this#MainActivity, "Driver $driver selected", Toast.LENGTH_SHORT).show()
myAdapter.notifyItemChanged(p2);
// myAdapter.notifyDataSetChanged()
}
override fun onNothingSelected(p0: AdapterView<*>?) {
}
}
return driver
}
Calling class:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerViewTripsheetlist.layoutManager = LinearLayoutManager(this)
val spnDriver: Spinner = findViewById(R.id.spnDriver)
var adapter = ArrayAdapter<String>(this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item)
conn(adapter, spnDriver)
}
private fun conn(adapter: ArrayAdapter<String>, spnDriver: Spinner) {
var tripsheetlist = ArrayList<DataModel>()
//populated by sql - removed for clarity
populatespinner(tripsheetlist, adapter)
var driver : String = Spinner(tripsheetlist)
var driverList : ArrayList<DataModel> = datafilter(tripsheetlist, driver)
tripsheetlist = driverList
weightsum(tvTotalweight, tripsheetlist)
totaldelNotes(tvTotaldelv,tripsheetlist)
runOnUiThread {
recyclerViewTripsheetlist.adapter = TableViewAdapter(tripsheetlist, driver, tvHeader, adapter)
}
}
Thank you for all and any help.
Related
I have an activity that has a recyclerview. Each item of the recyclerview has 3 components: spinner, EditText and an ImageButton
In the activity, there's an "add users" button that should save all the info in the recycleViewer to DB. To give more context, there's also an "add user" button that adds another item to the recycleViewer.
The problem is that when I call the saveUsers function from the activity, who calls the newUserAdapter.getUsers(), that function always returns the list of items of the RecycleView empty (the editText and the Spinner) even if the user has modified the info on the recycleView
Here is my activity
class AddUser : AppCompatActivity() {
private lateinit var binding: ActivityAddUserBinding
private lateinit var newUserAdapter : AddUserRecyclerViewAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAddUserBinding.inflate(layoutInflater)
newUserAdapter = AddUserRecyclerViewAdapter()
val b = User("","")
newUserAdapter.addItem(b)
binding.recyclerViewUser.adapter = newUserAdapter
setContentView(binding.root)
}
fun addNewUserRow(view: View) {
Timber.i("AddUser addNewUserRow called")
val b = User("","")
newUserAdapter.addItem(b)
}
fun saveUsers(view: View) {
if(newUserAdapter.itemCount > 0)
{
var usr = newUserAdapter.getUsers()
//TODO: save usr to DataBase
}
else
{
Snackbar.make(view, R.string.delete_user, Snackbar.LENGTH_LONG).show()
}
}
}
This is my User data class:
data class User (
var name: String = String(),
var department: String = String()
)
And my RecycleViewAdapter:
class AddUserRecyclerViewAdapter : RecyclerView.Adapter<AddUserRecyclerViewAdapter.AddUserViewHolder>() {
private var allUsers = ArrayList<User>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AddUserViewHolder {
Timber.i("User onCreateViewHolder")
val view = AddUserItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
val tempUser = AddUserViewHolder(view)
tempUser.deleteBtn.setOnClickListener {
Timber.i("NewUser setOnClickListener " + tempUser.bindingAdapterPosition)
if (this.itemCount > 1)
{
deleteItem(tempUser.bindingAdapterPosition)
}
else
{
//At least one item, we don't let delete the last one
Snackbar.make(it, R.string.delete_user, Snackbar.LENGTH_LONG).show()
}
}
return tempUser
}
override fun onBindViewHolder(holderUser: AddUserViewHolder, position: Int) {
Timber.i("NewUser onBindViewHolder $position")
val item = allUsers[position]
holderUser.nameEt.setText(item.name.toString())
}
private fun deleteItem(pos: Int) {
Timber.i("NewUser deleteItem $pos")
allUsers.removeAt(pos)
// call notifyDataSetChanged() to notify our adapter.
notifyItemRemoved(pos)
}
fun addItem(item: User) {
allUsers.add(item)
// call notifyDataSetChanged() to notify our adapter.
notifyItemInserted(allUsers.size -1)
}
fun getUsers(): ArrayList<User> {
return allUsers
}
override fun getItemCount(): Int {
Timber.i("NewUser getItemCount called" + allUsers.size)
return allUsers.size
}
inner class AddUserViewHolder(binding: AddUserItemBinding) :
RecyclerView.ViewHolder(binding.root) {
var nameEt: EditText = binding.etName
var deleteBtn : ImageButton = binding.btnDelete
var spinnerDepartment : Spinner = binding.spinnerDepartment
}
}
Edit
As it seems that someone downvoted for lack of information, let me say it in different words. This is the function in RecycleViewAdapter:
fun getUsers(): ArrayList<User> {
return allUsers
}
Who is called when a button is clicked from the activity:
fun saveUsers(view: View) {
if(newUserAdapter.itemCount > 0)
{
var usr = newUserAdapter.getUsers()
//TODO: save usr to DataBase
}
else
{
Snackbar.make(view, R.string.delete_user, Snackbar.LENGTH_LONG).show()
}
}
So the var usr is where I get a list of empty users, where I expected to get a list of users with the information filled in the RecycleView.
You should update the property of the user in the ArrayList when you are changing the text with an addTextChangedListener
override fun onBindViewHolder(holderUser: AddUserViewHolder, position: Int) {
Timber.i("NewUser onBindViewHolder $position")
val item = allUsers[position]
holderUser.nameEt.setText(item.name.toString())
holderUser.nameEt.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) { }
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { }
override fun onTextChanged(text: CharSequence?, p1: Int, p2: Int, p3: Int) {
// Update user instance in allUsers
allUsers[position].name = text.toString()
}
})
}
You may want also want to define an onItemSelectedListener on the Spinner to update the selected department as well.
What I want to reach is that the same RecyclerView shows different data depending on which button the App user pressed before in the MainActivity.kt.
In my MainActivity.kt I have two buttons, which both send the user to the same RecyclerView Activity (RecyclerViewLayout.kt) via Intent.
Example: The RecyclerView contains a picture of an apple and a banana. By pressing button A in MainActivity.kt, the RecyclerView in RecyclerViewLayout.kt should only show the apple. By pressing button B it should only show the banana. In my real app there are no fruits. but Tutorials, which should be filtered like described.
I gently ask for help here how to do that. Maybe there is also a better way to reach my target to filter the RecyclerView?
Thanks in Advance!
MainActivity.kt
class MainActivity : AppCompatActivity() {
private var binding:ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding?.root)
val buttonRecyclerView = findViewById<Button>(R.id.btn_recyclerview)
buttonRecyclerView.setOnClickListener {
val intent = Intent(this, RecyclerViewLayout::class.java)
startActivity(intent)
}
}}
RecyclerViewLayout.kt
class RecyclerViewLayout : AppCompatActivity() {
private lateinit var newRecylerview : RecyclerView
private lateinit var newArrayList : ArrayList<RecyclerViewDataClass>
private lateinit var tempArrayList : ArrayList<RecyclerViewDataClass>
lateinit var imageId : Array<Int>
lateinit var tutorialHeading : Array<String>
lateinit var tutorialText : Array<String>
lateinit var url : Array<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler_view_layout)
imageId = arrayOf(
R.drawable.brake,
R.drawable.brake,
)
tutorialHeading = arrayOf(
getString(R.string.scheibenbremse_lüften_heading),
getString(R.string.felgenbremse_richten_heading),
)
tutorialText = arrayOf(
getString(R.string.scheibenbremse_lüften_text),
getString(R.string.felgenbremse_richten_text),
)
url = arrayOf(
getString(R.string.url_a),
getString(R.string.url_b),
)
newRecylerview =findViewById(R.id.recyclerView)
newRecylerview.layoutManager = LinearLayoutManager(this)
newRecylerview.setHasFixedSize(true)
newArrayList = arrayListOf<RecyclerViewDataClass>()
tempArrayList = arrayListOf<RecyclerViewDataClass>()
getUserdata()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_item,menu)
val item = menu?.findItem(R.id.search_action)
val searchView = item?.actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
TODO("Not yet implemented")
}
override fun onQueryTextChange(newText: String?): Boolean {
tempArrayList.clear()
val searchText = newText!!.toLowerCase(Locale.getDefault())
if (searchText.isNotEmpty()){
newArrayList.forEach {
if (it.heading.toLowerCase(Locale.getDefault()).contains(searchText)){
tempArrayList.add(it)
}
}
newRecylerview.adapter!!.notifyDataSetChanged()
}else{
tempArrayList.clear()
tempArrayList.addAll(newArrayList)
newRecylerview.adapter!!.notifyDataSetChanged()
}
return false
}
})
return super.onCreateOptionsMenu(menu)
}
private fun getUserdata() {
for(i in imageId.indices){
val news = RecyclerViewDataClass(imageId[i],tutorialHeading[i],url[i])
newArrayList.add(news)
}
tempArrayList.addAll(newArrayList)
val adapter = RecyclerViewAdapter(tempArrayList)
newRecylerview.adapter = adapter
adapter.setOnItemClickListener(object : RecyclerViewAdapter.onItemClickListener{
override fun onItemClick(position: Int) {
val intent = Intent(this#RecyclerViewLayout,TutorialsActivity::class.java)
intent.putExtra("tutorialHeading",newArrayList[position].heading)
intent.putExtra("imageId",newArrayList[position].titleImage)
intent.putExtra("url",newArrayList[position].url)
intent.putExtra("tutorialText",tutorialText[position])
startActivity(intent)
}
})
}}
RecyclerViewAdapter.kt
class RecyclerViewAdapter(private val newsList : ArrayList<RecyclerViewDataClass>) : RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>(),
Filterable {
private lateinit var mListener : onItemClickListener
interface onItemClickListener{
fun onItemClick(position : Int)
}
fun setOnItemClickListener(listener: onItemClickListener){
mListener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.list_item,
parent,false)
return MyViewHolder(itemView,mListener)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = newsList[position]
holder.titleImage.setImageResource(currentItem.titleImage)
holder.tvHeading.text = currentItem.heading
}
override fun getItemCount(): Int {
return newsList.size
}
class MyViewHolder(itemView : View, listener: onItemClickListener) : RecyclerView.ViewHolder(itemView){
val titleImage : ShapeableImageView = itemView.findViewById(R.id.title_image)
val tvHeading : TextView = itemView.findViewById(R.id.tvHeading)
init {
itemView.setOnClickListener {
listener.onItemClick(adapterPosition)
}
}
}
override fun getFilter(): Filter {
TODO("Not yet implemented")
}}
RecyclerViewDataClass.kt
data class RecyclerViewDataClass(var titleImage: Int, var heading: String, val url: String)
**Tutorials Activity**
class TutorialsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tutorials)
val headingNews : TextView = findViewById(R.id.heading)
val mainNews : TextView = findViewById(R.id.news)
val imageNews : ImageView = findViewById(R.id.image_heading)
val bundle : Bundle?= intent.extras
val tutorialHeading = bundle!!.getString("tutorialHeading")
val imageId = bundle.getInt("imageId")
val tutorialText = bundle.getString("tutorialText")
val url = bundle.getString("url")
headingNews.text = tutorialHeading
mainNews.text = tutorialText
imageNews.setImageResource(imageId)
imageNews.setOnClickListener {
val openURL = Intent(Intent.ACTION_VIEW)
openURL.data = Uri.parse(url.toString())
startActivity(openURL)
}
}}
I believe you can pass data about which button is clicked using intents. Here's a link about that:
How to Pass custom object via intent in kotlin
For example, you can pass "A" if button A is clicked and "B" if button B is clicked, and then get that string in RecyclerViewLayout.kt to determine which elements should be shown.
According to me the simplest solution for doing this is you should have a boolean in preferences you can set preferences according to the button clicked and set data in your adapter to by getting the preferences value.
If you want to set data according to the button clicked
Other way is to pass the action onClick while starting a new Activity and getAction() in your second Activity.
This way you can also set data of your recyclerView by passing different data
I am using kotlin and android 8.0, I have 2 spinners in my code, 1 of them was created using a string array from resource and another was created with an ArrayList. For the spinner that was created with an ArrayList, when clicking on the item, it does not run the OnItemSelected function and does not update the spinner.
Here is my kotlin code for the spinner
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val modules = ArrayList<Module>()
val bufferedReader = BufferedReader(InputStreamReader(resources.openRawResource(R.raw.mod_code)))
var line = bufferedReader.readLine()
while(line != null) {
val values = line.split(",")
modules.add(Module(values[0].replace("\uFEFF", "").toInt(), values[1], values[2].replace("\uFEFF", "").toDouble()))
line = bufferedReader.readLine()
}
val moduleCodeArray = ArrayList<String>()
val yearSpinner: Spinner = findViewById(R.id.year)
yearSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val item = parent?.getItemAtPosition(position).toString()
Toast.makeText(parent?.context, "Selected: $item", Toast.LENGTH_LONG).show()
moduleCodeArray.clear()
for(module in modules) {
if(module.year == position + 1) {
moduleCodeArray.add(module.moduleCode)
}
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
ArrayAdapter.createFromResource(
this,
R.array.years,
R.layout.custom_spinner
).also { adapter ->
adapter.setDropDownViewResource(R.layout.custom_spinner_dropdown)
yearSpinner.adapter = adapter
}
println(moduleCodeArray)
val moduleCodeSpinner = findViewById<Spinner>(R.id.module_code)
moduleCodeSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val item = parent?.getItemAtPosition(position).toString()
Toast.makeText(parent?.context, "Selected: $item", Toast.LENGTH_LONG).show()
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
ArrayAdapter(
this,
R.layout.custom_spinner,
moduleCodeArray
).also { adapter ->
adapter.setDropDownViewResource(R.layout.custom_spinner_dropdown)
moduleCodeSpinner.adapter = adapter
}
}
}
EDIT: I have fixed the problem! In the code I provided, you can see my ArrayList being filled in an onItemSelected function, for some reason, the ArrayAdapter has to be in that function as well, so the correct code should look something like this.
val modules = ArrayList<Module>()
val bufferedReader = BufferedReader(InputStreamReader(resources.openRawResource(R.raw.mod_code)))
var line = bufferedReader.readLine()
while(line != null) {
val values = line.split(",")
modules.add(Module(values[0].replace("\uFEFF", "").toInt(), values[1], values[2].replace("\uFEFF", "").toDouble()))
line = bufferedReader.readLine()
}
val moduleCodeArray = ArrayList<String>()
val moduleCodeSpinner = findViewById<Spinner>(R.id.module_code)
val yearSpinner: Spinner = findViewById(R.id.year)
yearSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val item = parent?.getItemAtPosition(position).toString()
Toast.makeText(parent?.context, "Selected: $item", Toast.LENGTH_LONG).show()
moduleCodeArray.clear()
for(module in modules) {
if(module.year == position + 1) {
moduleCodeArray.add(module.moduleCode)
}
}
ArrayAdapter(
applicationContext,
R.layout.custom_spinner,
moduleCodeArray
).also { adapter ->
adapter.setDropDownViewResource(R.layout.custom_spinner_dropdown)
moduleCodeSpinner.adapter = adapter
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
ArrayAdapter.createFromResource(
this,
R.array.years,
R.layout.custom_spinner
).also { adapter ->
adapter.setDropDownViewResource(R.layout.custom_spinner_dropdown)
yearSpinner.adapter = adapter
}
moduleCodeSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val item = parent?.getItemAtPosition(position).toString()
Toast.makeText(parent?.context, "Selected: $item", Toast.LENGTH_LONG).show()
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
Your Code Seems correct , I have used the same code provided by you and it worked correctly.
May you have error in custom_spinner or custom_spinner_dropdown !![You can share these layouts ]
This is what I have done:
spinner example
I am trying to search through a recycler view with cards by allowing a user to search. When the user searches, the cards should "reorganize" to show according to the characters entered by the user. I have tried to do this but am having issues doing this. Any assistance is appreciated.
MainActivity.kt
class MainActivity : AppCompatActivity(), BottomSheetRecyclerViewAdapter.ListTappedListener {
private var customAdapter: CustomAdapter? = null
private var arrayListModel = ArrayList<Model>()
private lateinit var bottomSheetBehavior: CustomBottomSheetBehavior<ConstraintLayout>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val modelList = readFromAsset()
val adapterList = CustomAdapter(modelList, this)
customAdapter = CustomAdapter(arrayListModel, this#MainActivity)
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetLayout) as CustomBottomSheetBehavior
recyclerView.adapter = adapterList
recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
et_search.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (!s.isNullOrEmpty()) {
val searchList = ArrayList<Model>()
for (i in arrayListModel.indices) {
if (arrayListModel[i].name.toLowerCase().contains(s)) {
searchList.add(arrayListModel[i])
}
}
try {
customAdapter?.notifyDataSetChanged()
recyclerView.adapter = CustomAdapter(searchList, this#MainActivity)
} catch (e: Exception) {
e.printStackTrace()
}
} else {
customAdapter?.notifyDataSetChanged()
recyclerView.adapter = customAdapter
}
}
})
}
override fun onClickList(text: String) {
}
private fun readFromAsset(): List<Model> {
val modeList = mutableListOf<Model>()
val bufferReader = application.assets.open("android_version.json").bufferedReader()
val json_string = bufferReader.use {
it.readText()
}
val jsonArray = JSONArray(json_string);
for (i in 0..jsonArray.length() - 1) {
val jsonObject: JSONObject = jsonArray.getJSONObject(i)
val model = Model(jsonObject.getString("name"), jsonObject.getString("version"))
modeList.add(model)
}
return modeList
}
}
I might found your problem. Here you getting data val modelList = readFromAsset() but you are never assigning data to arrayListModel that your problem.
Assign the data to arrayListModel
val modelList = readFromAsset()
arrayListModel=modelList
Here's a clean approach you might want to consider/try:
Make your adapter implement the filterable interface.
Provide your own Filter object in which you implement your filtering logic (asynch).
You might as well use a SearchView instead of using onTextChange on an EditText.
So: onTextChange(newText) => call adapter.getFilter().filter(newText) => filtering happens in background (filter method performFiltering is called) => when filtered list ready (filter method publishResults is called), you push it to your adapter and notifyDataSetChanged.
Hope this helps.
Here's a clean example on how to implement this:
Example
I've implemented an ArrayAdapter to populate my Spinner view. The Spinner is working fine, however android is not detecting when I click an item in the spinner.
I've abided by all the requirements in the spinner example in the Android docs
including implementing AdapterView.OnItemSelectedListener to my Activity and overriding it's two methods OnItemSelectedListener and onNothingSelected, however, none of my Log statements in those methods print so they are not being called.
I've also set the listener to my spinner via choose_user.onItemSelectedListener = this#PlayerDetails.
Here's my activity:
class PlayerDetails : AppCompatActivity(), View.OnClickListener, TextWatcher, AdapterView.OnItemSelectedListener {
val TAG: String = "PlayerDetails"
val FirebaseTAG: String = "FirebaseDebug"
var numOfPlayers: Int = 1
var currentPlayer: Int = 1
var name: String = ""
var age: Int = 0
var genderId: Int = 0
var genderResult: String = ""
val db = FirebaseFirestore.getInstance()
var users: MutableList<String> = mutableListOf()
private lateinit var binding: ActivityPlayerDetailsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val sharedPref = this#PlayerDetails.getPreferences(Context.MODE_PRIVATE)
val applicationID: String? = sharedPref.getString("applicationID", null)
binding = DataBindingUtil.setContentView(this, R.layout.activity_player_details)
if (applicationID != null) {
db.collection("phones").document(applicationID)
.collection("users")
.get()
.addOnSuccessListener { result ->
for (document in result){
val name = document.get("name").toString()
users.add(name)
}
}
Log.d(FirebaseTAG, users.toString())
val spinnerAdaptor = ArrayAdapter<String>(this#PlayerDetails, android.R.layout.simple_spinner_item, users)
spinnerAdaptor.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
choose_user?.adapter = spinnerAdaptor
choose_user.onItemSelectedListener = this#PlayerDetails
}
val intent = getIntent()
numOfPlayers = intent.getIntExtra("number_of_players", 1)
next_details.setOnClickListener(this)
player_name.addTextChangedListener(this)
player_age.addTextChangedListener(this)
gender.setOnCheckedChangeListener(object: RadioGroup.OnCheckedChangeListener {
override fun onCheckedChanged(radiogroup: RadioGroup, checked: Int) {
if (fieldsArePopulated()) next_details.visibility = View.VISIBLE
}
})
}
override fun onItemSelected(parent: AdapterView<*>?, name: View?, position: Int, rowId: Long) {
val chosenName: String = parent?.getItemAtPosition(position).toString()
Log.d("ChosenName", chosenName)
Log.d("adapterclicked", "adapterclicked")
}
override fun onNothingSelected(parent: AdapterView<*>?) {
Log.d("Nothing", "NOTHINGCALLED")
}
...
Any idea what the problem is?
Also, when I select an item in the Spinner the view next to my spinner moves, so it's obviously being detected but onItemSelected() is still not being called.
I set an initial value to the users MutableList:
var users: MutableList<String> = mutableListOf("Choose User")
and now onItemSelected() is successfully being called.
I'm pretty sure onItemSelected returns an int of the item's position in array. So you have to save that as an int instead of string, and then add another variable that us a string and array[intSaved]
Edit
var chosenName = choose_user.onItemSelected("name")
try this
before :
override fun onItemSelected(parent: AdapterView<*>?, name: View?, position: Int, rowId: Long) {
val chosenName: String = parent?.getItemAtPosition(position).toString()
Log.d("ChosenName", chosenName)
Log.d("adapterclicked", "adapterclicked")
}
after :
override fun onItemSelected(parent: AdapterView<*>?, name: View?, position: Int, rowId: Long) {
val chosenNameTextView = parent!!.getChildAt(0) as TextView
Log.e("MainActivity","choose Spin : ${chosenNameTextView.text.toString()}")
}