Nathiel Paulino
Nathiel Paulino

Reputation: 544

Recyclerview is not getting updated in android

I'm trying to create a recycler by adding items per item, I already did by creating with a already existent list and it worked fine, but not by adding item per item. This is how I'm doing.

Fragment :

layoutManager =  LinearLayoutManager(context);
recyclerView?.layoutManager = layoutManager;
recyclerView?.adapter = SubCategoryAdapter();


 builder.setView(dialogLayout)
        builder.setPositiveButton("Salvar") { _, _ ->
           var model: SubCategoryModel = SubCategoryModel(alertTitleEdit.text.toString(),alertDescriptionEdit.text.toString(),null);
            adapter.run{
                addItems(model)
                notifyDataSetChanged()
            }
        }
        builder.show()

Adapter

class SubCategoryAdapter() : RecyclerView.Adapter<SubCategoryAdapter.SubCategoryHolder>() {

private var dataM: List<SubCategoryModel> = mutableListOf();

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SubCategoryHolder {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.card_sub_category, parent, false)
    return SubCategoryHolder(view);
}

override fun getItemCount(): Int {
    return dataM.count();
}

fun addItems(model: SubCategoryModel){
    dataM.toMutableList().add(model);
}


override fun onBindViewHolder(holder: SubCategoryHolder, position: Int) {
    var res = dataM[position];
    holder.title.text = res.Title;
    holder.description.text = res.Description

}

class SubCategoryHolder (val view: View) : RecyclerView.ViewHolder(view) {
    lateinit var title: TextView;
    lateinit var description: TextView;
    lateinit var price: TextView;
    var v: View = view;
    init {
        title = v.findViewById(R.id.textViewName);
        description = v.findViewById(R.id.description);
        price = v.findViewById(R.id.price);
    }
  }
}

Basically, nothing happens.

Upvotes: 0

Views: 65

Answers (2)

rahat
rahat

Reputation: 2056

private var dataM: List<SubCategoryModel> = mutableListOf();

The problem is with the type List it's not mutable.

In here dataM.toMutableList().add(model); the toMutableList().

The method does this

public fun <T> Collection<T>.toMutableList(): MutableList<T> {
    return ArrayList(this)
}

It returns a completely new instance, not the instance you have in your adapter.

You can do this

private var dataM: ArrayList<SubCategoryModel> = ArrayList();

and for adding item

fun addItems(model: SubCategoryModel){
    dataM.add(model);
    notifyItemInserted(dataM.count()-1);
}

Upvotes: 1

Quick learner
Quick learner

Reputation: 11457

You need to declare variable like this and use it

var adapter:SubCategoryAdapter()?=null

Then initialise it

layoutManager =  LinearLayoutManager(context)
recyclerView?.layoutManager = layoutManager
adapter = SubCategoryAdapter()
recyclerView?.adapter = adapter

Upvotes: 0

Related Questions