In my app, I am trying to add an item to my recycling view. When I add 1 item and call notifyDataSetChanged () there is no problem, only when I want to add a 2nd item and then call the same method the two added items appear 2 times. If I add a 3rd item the 1st added item still appears 2 times the 2nd item now appears 3 times and the 3rd added item also appears 3 times. I'm working with an adapter class for my recyclerview.
I've tried working with NotifyItemInserted(position-1) but it did not work.
Here are some snippets of my code:
My adapter class
class CategoriesAdapter(var clickListener: CategorieListener): ListAdapter<CategorieModel, CategoriesAdapter.CategorieViewHolder>(CategorieDiffCallback()) {
override fun getItemCount(): Int {
return super.getItemCount()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategorieViewHolder {
return CategorieViewHolder.from(parent)
}
override fun onBindViewHolder(holder: CategorieViewHolder, position: Int) {
val reis = getItem(position)
holder.bind(reis, clickListener, position)
}
class CategorieViewHolder private constructor(val binding: LayoutCategorieItemBinding) : RecyclerView.ViewHolder(binding.root){
fun bind(categorie: CategorieModel, clickListener: CategorieListener, position: Int?){
binding.categorie = categorie
var card = binding.catCard
itemView.setOnClickListener {
clickListener.onClick(categorie, card)
}
itemView.ib_delete.setOnClickListener {
clickListener.onDeleteClick(categorie, position!!)
}
binding.catCard.transitionName = categorie.naam
}
companion object {
fun from(parent:ViewGroup) : CategorieViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = LayoutCategorieItemBinding.inflate(layoutInflater, parent, false)
return CategorieViewHolder(binding)
}
}
}
class CategorieDiffCallback : DiffUtil.ItemCallback<CategorieModel>() {
override fun areItemsTheSame(oldItem: CategorieModel, newItem: CategorieModel): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: CategorieModel, newItem: CategorieModel): Boolean {
return oldItem == newItem
}
}
class CategorieListener(val clicklistener: (categorie: CategorieModel, view:MaterialCardView?, position:Int?) -> Unit){
fun onClick(categorie: CategorieModel, view: MaterialCardView) = clicklistener(categorie, view, 0)
fun onDeleteClick(categorie: CategorieModel, position: Int) = clicklistener(categorie, null, position)
}
}
My Fragment behind the scenes
private fun setAdapter() {
val adap = CategoriesAdapter(CategoriesAdapter.CategorieListener{ categorie, cardview, position ->
if(cardview == null){
deleteCategorie(categorie, position!!)
}else{
findNavController().navigate(CategoriesFragmentDirections.actionCategoriesFragmentToItemTakenFragment(categorie.naam,categorie))
}
})
binding.categories.apply {
layoutManager = LinearLayoutManager(this.context)
adapterobj = adap
adapter = adap
}
}
private fun setCardButtons() {
binding.btnAdd.setOnClickListener {
val categorie = CategorieModel(binding.catName.editText?.text.toString(),null,null, userId,0)
newCategorie(categorie)
}
binding.btnCancel.setOnClickListener {
toggleKeyboard()
}
}
private fun newCategorie(cat: CategorieModel){
//Toast.makeText(requireContext(), categories.size.toString(), Toast.LENGTH_SHORT).show()
model.createCategorie(cat)
model.categorieCreate.observe(viewLifecycleOwner, Observer {response ->
response?.let {
if(response.isSuccessful){
afterCreateActions(response.body()?.result)
}else{
afterErrorActions()
}
}
})
}
private fun afterCreateActions(cat: CategorieModel?) {
categories.add(cat!!)
adapterobj.notifyDataSetChanged()
toggleKeyboard()
toggleForm()
Snackbar.make(binding.mainView, "${cat?.naam} werd succesvol toevoegd!", Snackbar.LENGTH_LONG)
.setAnimationMode(Snackbar.ANIMATION_MODE_FADE)
.show()
}
The problem was that I was Observing liveData in an clicklistener, that was the main problem! Thanks to Ramakrishna Joshi n!
Visit answer!
Related
Hi I have a function inside my viewModel which make a pager and return a flow:
fun loadLastMoviesList(genreId: Int) = Pager(config = PagingConfig(10)) {
LastMoviesPaging(repository, genreId)
}.flow.cachedIn(viewModelScope)
and a click listener in my HomeFragment which whenever user click it execute the function with different genreId:
genresAdapter.setOnItemClickListener { genre, name ->
lastMoviesTitle.text = "$name Movies"
genre.id?.let { id ->
lifecycleScope.launchWhenCreated {
viewModel.loadLastMoviesList(id).collect {
lastMoviesAdapter.submitData(it)
}
}
}
}
my problem is that when I click on an Item of recyclerView and it send new request with new body
the new itm's appear on the top of last item in recyclerView I want to update the new list with the last list in the recycler view when the genreId change how can I do it??
Adapter:
class LastMoviesAdapter #Inject constructor(): PagingDataAdapter<Data, LastMoviesAdapter.ViewHolder>(differCallBack) {
private lateinit var binding: ItemHomeMoviesLastBinding
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LastMoviesAdapter.ViewHolder {
binding = ItemHomeMoviesLastBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder()
}
override fun onBindViewHolder(holder: LastMoviesAdapter.ViewHolder, position: Int) {
getItem(position)?.let { holder.setData(it) }
holder.setIsRecyclable(false)
}
inner class ViewHolder: RecyclerView.ViewHolder(binding.root){
fun setData(item: Data){
binding.apply {
movieNameTxt.text = item.title
movieRateTxt.text = item.imdbRating
movieCountryTxt.text = item.country
movieYearTxt.text = item.year
moviePosterImg.load(item.poster){
crossfade(true)
crossfade(800)
}
root.setOnClickListener{
onItemClickListener?.let {
it(item)
}
}
}
}
}
private var onItemClickListener: ((Data) -> Unit)? = null
fun setOnItemClickListener(listener: (Data) -> Unit){
onItemClickListener = listener
}
companion object{
val differCallBack = object : DiffUtil.ItemCallback<Data>(){
override fun areItemsTheSame(oldItem: Data, newItem: Data): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Data, newItem: Data): Boolean {
return oldItem == newItem
}
}
}
pagingSourceClase:
class LastMoviesPaging (private val repository: HomeRepository, private val genreId: Int): PagingSource<Int, Data>() {
override fun getRefreshKey(state: PagingState<Int, Data>): Int? {
return null
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Data> {
return try {
val currentPage = params.key ?: 1
Log.d("paging3", "paging running genre: $genreId")
val responseData = repository.lastMoviesList(genreId, currentPage).run {
body()?.data?.toString()?.let { Log.d("paging3", it) }
body()?.data ?: emptyList()
}
LoadResult.Page(responseData, if (currentPage == 1) null else -1 , if (responseData.isEmpty()) null else currentPage + 1)
}catch (e: Exception){
LoadResult.Error(e)
}
}
and I also want to save the flow in viewModel instead of resiving it directly in the HomeFragment
so any one can suggest a solution for my problem? I will provide more information if needed
I have a recycler view which has checkboxes as items. I want to make sure there cannot be selected more than 3 checkboxes. If 3 checkboxes are selected other checkboxes should not be selectable, only selected checkboxes should be able to be deselected. I am not sure if I need to implement that behaviour in adapter or fragment which holds adapter. This is how my adapter looks like:
class HomeAdapter(
private val listener: OnCheckBoxClickListener
) : ListAdapter<String, HomeAdapter.SurveyViewHolder>(HOME_COMPARATOR) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SurveyViewHolder {
val bind = ItemHomeBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return SurveyViewHolder(bind)
}
override fun onBindViewHolder(holder: SurveyViewHolder, position: Int) {
getItem(position)?.let { holder.bind(it) }
}
inner class SurveyViewHolder(
val binding: ItemHomeBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(answer: String) = with(binding) {
checkBox.text = answer
}
init {
binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
listener.onCheckBoxClickListener(
index = bindingAdapterPosition,
isChecked = isChecked,
answer = currentList[bindingAdapterPosition]
)
}
}
}
interface OnCheckBoxClickListener {
fun onCheckBoxClickListener(index: Int, isChecked: Boolean, answer: String)
}
companion object {
private val HOME_COMPARATOR = object : DiffUtil.ItemCallback<String>() {
override fun areItemsTheSame(oldItem: String, newItem: String): Boolean =
oldItem == newItem
override fun areContentsTheSame(oldItem: String, newItem: String): Boolean =
oldItem == newItem
}
}
}
So far, I have tried something like this in fragment:
private fun countCheckedCheckBoxes() = with(binding) {
var num = 0
for (i in 0..recyclerView.childCount) {
(recyclerView.getChildAt(i) as? CheckBox).also {
if (it?.isChecked == true) {
num += 1
}
}
}
if (num == 3) {
// TODO do something here
}
}
I am replacing a regular RecyclerView with a ListAdapter.
I am trying to implement a delete on swipe on the list within a fragment.
I have created the following ListAdapter class, the code for which is as follows:
class NewsAdapter(private val listener: OnItemClickListener) : ListAdapter<Article, NewsAdapter.ArticleViewHolder>(DiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
val binding = ItemArticlePreviewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ArticleViewHolder(binding)
}
override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
val currentArticle = getItem(position)
holder.bind(currentArticle)
}
inner class ArticleViewHolder(private val binding: ItemArticlePreviewBinding): RecyclerView.ViewHolder(binding.root) {
init {
binding.apply {
root.setOnClickListener {
val position = adapterPosition
if(position != RecyclerView.NO_POSITION) {
val article = getItem(position)
listener.onItemClick(article)
}
}
}
}
fun bind(article: Article) {
binding.apply {
Glide.with(itemView.context).load(article.urlToImage).into(ivArticleImage)
tvSource.text = article.source.name
tvTitle.text = article.title
tvDescription.text = article.description
tvPublishedAt.text = article.publishedAt
}
}
}
/*
* Had to create my own function here since for some reason,
* newsAdapter.currentList is not working in any fragment
* */
fun getArticleAt(position: Int): Article {
return getItem(position)
}
interface OnItemClickListener {
fun onItemClick(article: Article)
}
class DiffCallback : DiffUtil.ItemCallback<Article>() {
override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean {
return oldItem.url == newItem.url
}
override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean {
return oldItem == newItem
}
}
}
Within the fragment where this list resides, I have the following:
...
lateinit var newsAdapter: NewsAdapter
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
...
ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
val article = newsAdapter.getArticleAt(position) // this works, but it is not what I want
viewModel.deleteArticle(article)
Snackbar.make(view, "Article successfully deleted.", Snackbar.LENGTH_LONG)
.apply {
setAction("Undo") {
viewModel.saveArticle(article)
}
show()
}
}
}).attachToRecyclerView(rvSavedNews)
...
}
...
Notice above, that I had to call:
val article = newsAdapter.getArticleAt(position)
within the fragment, since for some reason, I cannot use currentList as follows:
val article = newsAdapter.currentList[position]
The delete on swipe works just fine from what I can tell, however, I don't think I am always getting the most current list. Note: calling submitList on my adapter works just fine for other purposes. currentList seems to not be callable and I cannot figure out why.
I create an app to fetch some data from the REST API. I had some issues with recycler view scrolling. When I scroll down and then scroll up all the items will be messed up. I searched in stack overflow and find an answer. The answer said that we should add setHasStableIds = true to our adapter and add getItemViewType to our adapter class. I did and it worked fine but the new problem came.
the image of the items should load sequentially. For instance, if the user scrolled down to item 200 he/she should wait until all previous items load it images.
This is my adapter code
class MovieAdapter : PagingDataAdapter<Movie,MovieAdapter.MovieViewHolder>(DiffUtilCallback()) {
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
try {
holder.bind(getItem(position)!!)
}catch (e : Exception){
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.movie_list_item,parent,false)
return MovieViewHolder(view)
}
override fun getItemViewType(position: Int): Int {
return position
}
/////
class MovieViewHolder(view : View) : RecyclerView.ViewHolder(view){
private val imgMoviePoster = view.findViewById<ImageView>(R.id.imgImagePoster)
private val txtMovieTitle = view.findViewById<TextView>(R.id.txtMovieTitle)
private val txtMovieReleaseDate = view.findViewById<TextView>(R.id.txtMovieReleaseDate)
fun bind(movie : Movie){
txtMovieTitle.text = movie.title
txtMovieReleaseDate.text = movie.releaseDate
val moviePosterUrl = POSTER_BASE_URL + movie.posterPath
/*Glide.with(imgMoviePoster)
.load(moviePosterUrl)
.into(imgMoviePoster)*/
Picasso.get().load(moviePosterUrl).into(imgMoviePoster)
}
}
/////
class DiffUtilCallback : DiffUtil.ItemCallback<Movie>(){
override fun areItemsTheSame(oldItem: Movie, newItem: Movie): Boolean {
return newItem.id == oldItem.id
}
override fun areContentsTheSame(oldItem: Movie, newItem: Movie): Boolean {
return newItem == oldItem
}
}
}
This is my code for recycler view and view model (inside main activity)
private fun initRecyclerView(){
recyclerViewPopMovie.apply {
layoutManager = GridLayoutManager(this#MainActivity,2)
movieAdapter = MovieAdapter()
adapter = movieAdapter
}
}
private fun initViewModel(){
lifecycleScope.launchWhenCreated {
viewModel.getContent().collectLatest {
movieAdapter.submitData(it)
movieAdapter.setHasStableIds(true)
}
}
}
I am working with RecyclerView and the issue is when is click on one item it become selected.after That when click on second item the first and second item both are selected at the same time.
Code For Onclick:
init {
itemView.setOnClickListener {
modesList[adapterPosition].isSelected = true
val modelWrapper = modesList[adapterPosition]
val formatModel = modelWrapper.mode
itemListener.recyclerViewListClicked(
formatModel,
formatModel.getId(),
formatModel.modeName,
formatModel.modeName_Number,
formatModel.modeBrightnessProgressBar,
formatModel.modeSpeedProgressBar,
formatModel.colorValues,
adapterPosition
)
}
You should get the position of an item in your adapter and pass it to the activity or fragment and simply do your job.
Here you can see an example.
class MyAdapter : RecyclerView.Adapter<MyAdapter.MyAdapterViewHolder>() {
inner class MyAdapterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
private val differCallback = object : DiffUtil.ItemCallback<Item>() {
override fun areItemsTheSame(oldItem: YourEntityObject, newItem: YourEntityObject): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: YourEntityObject, newItem: YourEntityObject): Boolean {
return oldItem == newItem
}
}
val differ = AsyncListDiffer(this, differCallback)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyAdapterViewHolder{
return MyAdapterViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false))
}
override fun getItemCount(): Int {
return differ.currentList.size
}
private var onItemClickListener: ((YourEntityObject) -> Unit)? = null
override fun onBindViewHolder(holder: MyAdapterViewHolder, position: Int) {
val info = differ.currentList[position]
holder.itemView.apply {
setOnClickListener {
onItemClickListener?.let { it(repoInfo) }
}
}
}
fun setOnItemClickListener(listener: (YourEntityObject) -> Unit) {
onItemClickListener = listener
}
}
Now in your fragment just simply write as following.
private lateinit var myAdapter: MyAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
adapterOperation()
}
private fun adapterOperation() {
with(myAdapter) {
setOnItemClickListener {
toast(it.your_entity_property)// for example toast the name of list item
}
}
}
private fun setupRecyclerView() {
adapter = MyAdapter()
your_recyclerveiw.apply {
adapter = myAdapter
layoutManager = LinearLayoutManager(activity)
}
}
}
You have to declare itemid and itemviewtype in your Recycler Adapter to overcome this.
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}