Saving EditText content in RecyclerView on Kotlin - android

Similarly to Saving EditText content in RecyclerView, I have an implementation of a pair of EditTexts to fill inside every row of a RecyclerView. But my position variable inside my TextWatcher is always returning 0, even after the updatePosition function been called.
the Lod.d at afterTextChanged() on both Watchers always shows that position is 0, even after filling the editText at the 3rd position.
I can see that updatePosition goes from 0 to areasimportadas.size during the onBindViewHolder function, but it doesn't happen for onTextChanged.
class importItemsAdapter(val areasImportadas: MutableList, val inclinaLida: MutableList, val desvLido: MutableList) : RecyclerView.Adapter() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val cellForRow = layoutInflater.inflate(R.layout.import_items,parent,false)
return CustomViewHolder(cellForRow)
}
override fun getItemCount(): Int {
return areasImportadas.size
}
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
holder.itemView.importNum.text = (position+1).toString()
holder.itemView.importArea.text = areasImportadas[position]
Watcher1().updatePosition(holder.adapterPosition)
Watcher2().updatePosition(holder.adapterPosition)
holder.itemView.importInclina.addTextChangedListener(Watcher1())
holder.itemView.importDesv.addTextChangedListener(Watcher2())
}
class CustomViewHolder(view: View): RecyclerView.ViewHolder(view)
private inner class Watcher1 : TextWatcher {
var position = 0
fun updatePosition(positionExt: Int) {
this.position = positionExt
Log.d("Registro", this.position.toString())
}
override fun afterTextChanged(arg0: Editable) {
inclinaLida[position]= arg0.toString()
Log.d("Registro", "Inclinação $position: ${inclinaLida[position]}")
}
override fun beforeTextChanged(arg0: CharSequence, arg1: Int, arg2: Int, arg3: Int) {}
override fun onTextChanged(s: CharSequence, a: Int, b: Int, c: Int) {
}
}
private inner class Watcher2 : TextWatcher {
var position = 0
fun updatePosition(positionExt: Int) {
position = positionExt
Log.d("Registro", position.toString())
}
override fun afterTextChanged(arg0: Editable) {
Log.d("Registro", "Desvio ${position}: ${desvLido[position]}")
}
override fun beforeTextChanged(arg0: CharSequence, arg1: Int, arg2: Int, arg3: Int) {
}
override fun onTextChanged(s: CharSequence, a: Int, b: Int, c: Int) {
desvLido[position]=s.toString()
}
}
}
I needed to be able to store each EditText content under its proper position on both lists (desvLido and inclinaLida)

What was missing was calling an instance:
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
holder.itemView.importNum.text = (position+1).toString()
holder.itemView.importArea.text = areasImportadas[position]
val watcher1 = Watcher1()
watcher1.updatePosition(holder.adapterPosition)
holder.itemView.importInclina.addTextChangedListener(watcher1)
}
Now position returns the correct value.

Related

How to display an empty item of recyclerview so that user can fill the data into it?

I am new to kotlin-android and I am developing a stock keeping unit, where in one fragment i need to load the data into recycler view using arraylist but also, i need one blank item, where user can enter his own data and once he fills that blank item, a new blank item should be created.
class RecyclerViewAdapterU (val dataList:ArrayList<ModelClass>): RecyclerView.Adapter<RecyclerViewAdapterU.ViewHolder>() {
var _binding: UploadItemViewBinding? = null
val binding get() = _binding!!
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerViewAdapterU.ViewHolder {
val v =
LayoutInflater.from(parent.context).inflate(R.layout.upload_item_view, parent, false)
_binding = UploadItemViewBinding.bind(v)
return ViewHolder(binding.root)
}
fun getUpdatedDetails(skucode:String,pos:Int){
// val skuDetails:ArrayList<ModelClass>
val call: Call<List<ModelClass>>? =
ApiClient.instance?.myApi?.getfromsku(skucode)!!
call!!.enqueue(object : Callback<List<ModelClass>?> {
override fun onResponse(
call: Call<List<ModelClass>?>,
response: Response<List<ModelClass>?>
) {
if (!response.body().isNullOrEmpty()) {
val skuDetails: ArrayList<ModelClass> = response.body() as ArrayList<ModelClass>
//
// if (!skuDetails.isNullOrEmpty()) {
val x = dataList[pos].sku_code
if (skuDetails[pos].sku_code != x) {
//for (i in skuDetails.indices){
println(skuDetails[pos].sku_code)
println(".........$pos")
dataList.removeAt(pos)
dataList.add(pos, skuDetails[0])
skuDetails.clear()
notifyItemChanged(pos)
//}
}
}
}
override fun onFailure(call: Call<List<ModelClass>?>, t: Throwable) {
}
})
}
override fun onBindViewHolder(holder: ViewHolder, #SuppressLint("RecyclerView") position: Int) {
bindItems(dataList[position])
holder.getStock()
holder.updateStockDetail()
}
fun bindItems(data: ModelClass) {
binding.apply {
itemquant.text=data.item_quant
uploadItemName.text = data.item_name
uploadMfg.text = data.mfg
skuStock.setText(data.item_stock.toString())
skuCode.setText(data.sku_code)
}
}
override fun getItemCount(): Int {
return dataList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun getStock() {
binding.skuStock.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun afterTextChanged(editable: Editable) {
if (binding.skuStock.isFocused){
for (i in 0 until RecyclerViewAdapter.ob.dataSelected.size){
if (editable.toString().trim()!=""){
var x= editable.toString().trim().toInt()
RecyclerViewAdapter.ob.dataSelected[adapterPosition].item_stock=x
//getting current itemstock before pushing update.
//assigning latest itemstock to the data for the update
}
}
}}
})
}
fun updateStockDetail(){
binding.skuCode.addTextChangedListener(object : TextWatcher{
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
}
override fun afterTextChanged(editable: Editable) {
//binding.skuCode.removeTextChangedListener(this)
var pos:Int=adapterPosition
var x= editable.toString().trim()
//RecyclerViewAdapter.ob.dataSelected[adapterPosition].sku_code=x
println("$x in textwatcher and $pos")
//getting edited text and calling the function to get updated details.
getUpdatedDetails(x,pos)
// binding.skuCode.addTextChangedListener(this)
}
})
}
}
}
I have couple of bugs in the adapter too, for example, i cant change textwatcher more than once.
If somebody could help me with this, would be very glad.
ob.data.selected comes from another recyclerview adapter.
One way you can do this is by using a different view type for the blank item that will always stay at the very top (or bottom if you prefer). Once the blank item is filled up then a new non-blank item with a different view type will be added to your list.
More info about view types here: Android and Kotlin: RecyclerView with multiple view types

Can somebody review my RecyclerView adapter? Text watcher crashes after 4-5 changes in text

My textchanged listener is for updatestockdetail() is working very weirdly, it crashes after 4-5 times changing the text and it also shows the first item when i change the text for the third time. I believe i am ding something majorly wrong. If somebody could help me, would be very glad.
class RecyclerViewAdapterU (val dataList:ArrayList<ModelClass>): RecyclerView.Adapter<RecyclerViewAdapterU.ViewHolder>() {
var _binding: UploadItemViewBinding? = null
val binding get() = _binding!!
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerViewAdapterU.ViewHolder {
val v =
LayoutInflater.from(parent.context).inflate(R.layout.upload_item_view, parent, false)
_binding = UploadItemViewBinding.bind(v)
return ViewHolder(binding.root)
}
fun getUpdatedDetails(skucode:String,pos:Int){
// val skuDetails:ArrayList<ModelClass>
val call: Call<List<ModelClass>>? =
ApiClient.instance?.myApi?.getfromsku(skucode)!!
call!!.enqueue(object : Callback<List<ModelClass>?> {
override fun onResponse(
call: Call<List<ModelClass>?>,
response: Response<List<ModelClass>?>
) {
val skuDetails=response.body()
if (!skuDetails.isNullOrEmpty()) {
val x=dataList[pos].sku_code
for (i in skuDetails.indices){
println(skuDetails[i].sku_code)
println(".........$pos")
if (skuDetails[i].sku_code!=x){
dataList.removeAt(pos)
dataList.add(pos,skuDetails[i])
notifyItemChanged(pos)
}
}
}
}
override fun onFailure(call: Call<List<ModelClass>?>, t: Throwable) {
}
})
}
override fun onBindViewHolder(holder: ViewHolder, #SuppressLint("RecyclerView") position: Int) {
bindItems(dataList[position])
holder.getStock()
holder.updateStockDetail()
}
fun bindItems(data: ModelClass) {
binding.apply {
itemquant.text=data.item_quant
uploadItemName.text = data.item_name
uploadMfg.text = data.mfg
skuStock.setText(data.item_stock.toString())
skuCode.setText(data.sku_code)
}
}
override fun getItemCount(): Int {
return dataList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun getStock() {
binding.skuStock.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun afterTextChanged(editable: Editable) {
if (binding.skuStock.isFocused){
for (i in 0 until RecyclerViewAdapter.ob.dataSelected.size){
if (editable.toString().trim()!=""){
var x= editable.toString().trim().toInt()
RecyclerViewAdapter.ob.dataSelected[adapterPosition].item_stock=x
//getting current itemstock before pushing update.
//assigning latest itemstock to the data for the update
}
}
}}
})
}
fun updateStockDetail(){
binding.skuCode.addTextChangedListener(object : TextWatcher{
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
}
override fun afterTextChanged(editable: Editable) {
binding.skuCode.removeTextChangedListener(this)
var pos:Int=adapterPosition
var x= editable.toString().trim()
//RecyclerViewAdapter.ob.dataSelected[adapterPosition].sku_code=x
println("$x in textwatcher and $pos")
//getting edited text and calling the function to get updated details.
getUpdatedDetails(x,pos)
binding.skuCode.addTextChangedListener(this)
}
})
}
}
}
Before anyone asks, ob.dataselected comes from another rcv adapter. There is a issue in notifyitemchanged(pos) in getupdateddetails() which is called from updateStockDetail().
binding.skuCode.addTextChangedListener(this)
above code is causing the loop. You have to get rid of this line.

How to stop textchangedlistener being executed infinitely after changing text once?

I have been working on a stock keeping application as a demo to learn kotlin and android studio, I have added textchangedlistener in a recycler view item, which everytime it text is changed, gets information from Api and displays new item on textview. This works good for only one time, After that it keeps infinitely changing. please check video for better understanding : ScreenRecording .
Here is my rcv adapter :
class RecyclerViewAdapterU (val dataList:ArrayList<ModelClass>): RecyclerView.Adapter<RecyclerViewAdapterU.ViewHolder>() {
var _binding: UploadItemViewBinding? = null
val binding get() = _binding!!
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerViewAdapterU.ViewHolder {
val v =
LayoutInflater.from(parent.context).inflate(R.layout.upload_item_view, parent, false)
_binding = UploadItemViewBinding.bind(v)
return ViewHolder(binding.root)
}
override fun onBindViewHolder(holder: ViewHolder, #SuppressLint("RecyclerView") position: Int) {
bindItems(dataList[position])
holder.getStock()
holder.updateStockDetail()
}
fun bindItems(data: ModelClass) {
binding.apply {
itemquant.text=data.item_quant
uploadItemName.text = data.item_name
uploadMfg.text = data.mfg
skuStock.setText(data.item_stock.toString())
skuCode.setText(data.sku_code)
}
}
fun getUpdatedDetails(skucode:String,pos:Int){
val call: Call<List<ModelClass>>? =
ApiClient.instance?.myApi?.getfromsku(skucode)!!
call!!.enqueue(object : Callback<List<ModelClass>?> {
override fun onResponse(
call: Call<List<ModelClass>?>,
response: Response<List<ModelClass>?>
) {
val skuDetails=response.body()
if (skuDetails != null) {
dataList.removeAt(pos)
for (i in skuDetails){
println(i.item_name)
dataList.add(pos,i)
}
notifyItemChanged(pos)
}
}
override fun onFailure(call: Call<List<ModelClass>?>, t: Throwable) {
}
})
}
override fun getItemCount(): Int {
return dataList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun getStock() {
binding.skuStock.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun afterTextChanged(editable: Editable) {
for (i in 0 until RecyclerViewAdapter.ob.dataSelected.size){
if (editable.toString().trim()!=""){
var x= editable.toString().trim().toInt()
RecyclerViewAdapter.ob.dataSelected[adapterPosition].item_stock=x
//getting current itemstock before pushing update.
//assigning latest itemstock to the data for the update
}
}
}
})
}
fun updateStockDetail(){
binding.skuCode.addTextChangedListener(object : TextWatcher{
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
}
override fun afterTextChanged(editable: Editable) {
var x:String=""
var pos:Int=adapterPosition
for (i in 0 until RecyclerViewAdapter.ob.dataSelected.size){
if (editable.toString().trim()!=""){
x=editable.toString().trim()
//RecyclerViewAdapter.ob.dataSelected[adapterPosition].sku_code=x
println("$x in if")
}
}
//println(RecyclerViewAdapter.ob.dataSelected[adapterPosition].sku_code)
//getting edited text and calling the function to get updated details.
getUpdatedDetails(x,pos)
binding.skuStock.removeTextChangedListener(this)
}
})
}
}
}
If possible please review my code and let me know what are things i need to work on.
Note: ob.dataselected is a global variable from another recyclerview adapter.
Textchangedlistener i am talking about is in the fun updateStockDetail()
In the documentation for afterTextChanged we see the following:
This method is called to notify you that, somewhere within s, the text has been changed. It is legitimate to make further changes to s from this callback, but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively.
(The emphasis is mine.) I don't see where you remove the text watcher before changing the text, so you may be in an infinite loop.
To remove the text watcher use removeTextChangedListener. You can replace the text watcher after making changes.

Another "RecyclerView duplicating items" question

I'm having this problem and spent hours exploring different solutions found here but couldn't figure it out. I have a RecyclerView with a RadioGroup (with two RadioButton) and an EditText. As expected, the text keeps getting duplicated on scroll and the "original" gets deleted. The same happens with the radio buttons. I've tried to save on another array backup the values when the view is recycled but couldn't solve the duplicating issue.
Here's my adapter
class ServicesCheckoutAdapter(var context: Context,
var servicesList: List<Service>) : RecyclerView.Adapter<ServicesCheckoutAdapter.ViewHolder>() {
private lateinit var onRadioGroupClickListener: OnRadioGroupClickListener
private lateinit var onTextChangedListener: OnTextChangedListener
private lateinit var onServiceClickListener: OnServiceClickListener
private var externalArray = mutableListOf<String>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.services_list_item,
parent, false)
val viewHolder = ViewHolder(view)
val position = viewHolder.adapterPosition
view.setOnClickListener {
if (onServiceClickListener != null) {
onServiceClickListener.onServiceClick(view, servicesList[position].id, position)
}
}
return viewHolder
}
override fun getItemId(position: Int): Long {
return super.getItemId(position)
}
override fun getItemViewType(position: Int): Int {
return super.getItemViewType(position)
}
interface OnServiceClickListener {
fun onServiceClick(view: View, serviceId: Int, position: Int)
}
fun setOnServiceClickListener(listener: OnServiceClickListener)
{
onServiceClickListener = listener
}
interface OnRadioGroupClickListener {
fun onRadioGroupClick(buttonId: Int, serviceId: Int, position: Int) {}
}
fun setOnRadioButtonClickListener(listener: OnRadioGroupClickListener) {
onRadioGroupClickListener = listener
}
interface OnTextChangedListener{
fun onTextChanged(position: Int, text: String)
}
fun setOnTextChangedListener(listener: OnTextChangedListener){
onTextChangedListener = listener
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
Log.d("recycler", "lista: ${servicesList[position].serviceSolution}")
holder.edtSolution.removeTextChangedListener(holder.watcher)
holder.bind(context,
servicesList[position].id,
servicesList[position].name,
servicesList[position].serviceSolved,
servicesList[position].serviceSolution,
onRadioGroupClickListener,
onTextChangedListener,
position)
}
override fun getItemCount(): Int {
return servicesList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var radioGroup = itemView.findViewById<RadioGroup>(R.id.radioGroupService)
val edtSolution = itemView.findViewById<EditText>(R.id.editTextCheckoutDesc)
var watcher: TextWatcher? = null
fun bind(context: Context,
serviceId: Int,
serviceName: String,
serviceSolved: Boolean,
serviceSolution: String,
onRadioGroupClickListener: OnRadioGroupClickListener,
onTextChangedListener: OnTextChangedListener,
position: Int
) {
itemView.findViewById<TextView>(R.id.serviceTitle)
.text = context.resources
.getString(R.string.service_title_comma, serviceName)
itemView.findViewById<RadioGroup>(R.id.radioGroupService)
.setOnClickListener {
onRadioGroupClickListener
.onRadioGroupClick(
(it as RadioGroup).checkedRadioButtonId, serviceId, adapterPosition)
}
if (serviceSolved) {
radioGroup.find<RadioButton>(R.id.radioBtnYes).isChecked = true
radioGroup.find<RadioButton>(R.id.radioBtnNo).isChecked = false
} else {
radioGroup.find<RadioButton>(R.id.radioBtnYes).isChecked = false
radioGroup.find<RadioButton>(R.id.radioBtnNo).isChecked = true
}
edtSolution.addTextChangedListener(object: TextWatcher{
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onTextChangedListener.onTextChanged(position, s.toString())
}
override fun afterTextChanged(s: Editable?) {
}
})
}
}
}
And here's the adapter initialization on the activity
serviceList = occurrence.services
servicesAdapter = ServicesCheckoutAdapter(this, serviceList)
recyclerViewServices.adapter = servicesAdapter
recyclerViewServices.layoutManager = LinearLayoutManager(this)
servicesAdapter.setOnRadioButtonClickListener(object : ServicesCheckoutAdapter.OnRadioGroupClickListener {
override fun onRadioGroupClick(buttonId: Int, serviceId: Int, position: Int) {
super.onRadioGroupClick(buttonId, serviceId, position)
when (buttonId) {
R.id.radioBtnYes -> {
serviceList[position].serviceSolved = true
servicesAdapter.notifyDataSetChanged()
}
R.id.radioBtnNo -> {
serviceList[position].serviceSolved = false
servicesAdapter.notifyDataSetChanged()
}
}
}
})
servicesAdapter.setOnTextChangedListener(object : ServicesCheckoutAdapter.OnTextChangedListener{
override fun onTextChanged(position: Int, text: String) {
serviceList[position].serviceSolution = text
}
})
RecyclerView isn't usually made for Input views. As Android saves the input of a view depending on its ID, your RecyclerView has X number of views that all have the same ID, hence they all use the same state.
A solution to this would be saving your input state manually in recycle method, and restoring it in bind method.
So if you have 20 items, you have 20 states. Initially they are all empty or defaulted, and change when needed to save.
A more simpler approach would be using a LinearLayout or similar Layouts to accomplish your goal, but that depends on how many items you have and how many views that will contain.
You still need to be careful for the View ID part, though
I've tried to use a ListView but the keyboard went crazy changing focus. Decided to keep the RecyclerView and since my dynamic list isn't so large, I used the
holder.setIsRecyclable(false);
on the OnBindViewHolder() method and it solved my issue. Thanks everyone for the help

Android Kotlin recyclerview with EditText

I have a recyclerview where each view contains a TextView and an EditText. The part where I am stuck is when I start typing in any of the row's EditText box, it automatically updates another row further down the list. I know this is occurring because of the whole recycling aspect of recyclerview and the same view is re-used for the rows further down. I just don't know how to implement this correctly.
class TodoAdapter(private val tasks : List<TodoItem>) : RecyclerView.Adapter<TodoAdapter.ViewHolder>() {
inner class ViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
var editText = view.findViewById<EditText>(R.id.edit_text)
init {
editText.addTextChangedListener(object : TextWatcher{
override fun afterTextChanged(s: Editable?) {
tasks[adapterPosition].task = s.toString()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.todo_item,parent,false)
return ViewHolder(view)
}
override fun getItemCount() = tasks.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = tasks[position]
holder.editText.setText(item.task)
}
}
class TodoItem(var task: String = "")
editText.addTextChangedListener(object TextWatcher() {
override fun afterTextChanged(s : Editable) {
item.textFieldValue = s.toString()
}
});
Put textChangeListener inside init block this should work
#MuhammadAhmed
Data class
class todolist(var hours: String, var task: String)
Adapter
override fun onBindViewHolder(holder: TodoAdapter.TodoViewHolder, position: Int) {
val currentItem = todo[position]
holder.todo.text = currentItem.hours
holder.task.text = currentItem.task
holder.task.addTextChangedListener(object: TextWatcher{
override fun afterTextChanged(s: Editable?) {
currentItem.task = s.toString()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
}

Categories

Resources