RecyclerView only displays first item - android

So, I am creating a cocktail app, based on the https://www.thecocktaildb.com/ api. Thus far, I have only created a screen to display options based on the ingredient I put in the search bar (search bar is not done yet). Yet when I run the app, only the first entry is displayed
By putting Log.e("TAG", "$position") inside of my onBindViewHolder, of the adapter, I saw that the position variable never increases from 0
class CocktailsAdapter: RecyclerView.Adapter<CocktailsAdapter.CocktailsViewHolder>() {
inner class CocktailsViewHolder(val binding: ItemCocktailPreviewBinding) :
RecyclerView.ViewHolder(binding.root)
private val differCallback = object : DiffUtil.ItemCallback<CocktailsByBaseDto>() {
override fun areItemsTheSame( oldItem: CocktailsByBaseDto, newItem: CocktailsByBaseDto): Boolean {
return oldItem.drinks[0].idDrink == newItem.drinks[0].idDrink
}
override fun areContentsTheSame(oldItem: CocktailsByBaseDto, newItem: CocktailsByBaseDto): Boolean {
return oldItem.drinks[0] == newItem.drinks[0]
}
}
val differ = AsyncListDiffer(this, differCallback)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CocktailsViewHolder {
return CocktailsViewHolder(
ItemCocktailPreviewBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: CocktailsViewHolder, position: Int) {
val binding = holder.binding
val cocktail = differ.currentList[position]
holder.itemView.apply {
Glide.with(this).load(cocktail.drinks[position].strDrinkThumb).into(binding.imgCocktailsMainRecyclerViewImage)
binding.tvCocktailsMainRecyclerViewTitle.text = cocktail.drinks[position].strDrink
Log.e("TAG", "$position")
setOnClickListener {
onItemClickListener?.let { it(cocktail) }
}
}
}
override fun getItemCount(): Int {
return differ.currentList.size
}
private var onItemClickListener: ((CocktailsByBaseDto) -> Unit)? = null
fun setOnItemClickListener(listener: (CocktailsByBaseDto) -> Unit) {
onItemClickListener = listener
}
I have tried both position and 0 (which makes more sense) inside val cocktail = differ.currentList[position], but neither gave me a different result

Fixed it by changing the class I had passed to DiffUtil.ItemCallback

Related

RecyclerView items not displaying

The title says, I'm trying to load items into a recyclerview but the items doesn't displaying.
I'm getting the items from the api, using retrofit and mutablelivedata, I'm getting the items right, and the adapter gets the items (there are 3 items, and the adapter gets the 3 items), but the items doesn't display on the UI.
Here is my code:
Adapter.java
class EstablecimientosAdapter : ListAdapter<EstablecimientoModel, EstablecimientosViewHolder>(
DIFF_CALLBACK
) {
companion object {
val DIFF_CALLBACK: DiffUtil.ItemCallback<EstablecimientoModel> =
object : DiffUtil.ItemCallback<EstablecimientoModel>() {
override fun areItemsTheSame(
oldItem: EstablecimientoModel,
newItem: EstablecimientoModel
): Boolean {
return oldItem.hash == newItem.hash
}
override fun areContentsTheSame(
oldItem: EstablecimientoModel,
newItem: EstablecimientoModel
): Boolean {
return oldItem.nombre == newItem.nombre
}
}
}
private val mEstablecimientos: MutableList<EstablecimientoModel> = mutableListOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EstablecimientosViewHolder {
val binding = RowEstablecimientoBinding.inflate(
LayoutInflater.from(parent.context), parent, false
)
return EstablecimientosViewHolder(binding)
}
override fun onBindViewHolder(holder: EstablecimientosViewHolder, position: Int) {
val establecimiento = getItem(position)
holder.bindItem(establecimiento!!)
}
override fun getItemCount(): Int {
return mEstablecimientos.size
}
fun addMoreEstablecimientos(newEstablecimientos: List<EstablecimientoModel>) {
mEstablecimientos.addAll(newEstablecimientos)
submitList(mEstablecimientos)
}
class EstablecimientosViewHolder(val binding: RowEstablecimientoBinding) :
RecyclerView.ViewHolder(
binding.root
) {
fun bindItem(establecimiento: EstablecimientoModel) {
binding.setVariable(BR.establecimiento, establecimiento)
}
}
}
recycler_view.xml
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvEstablecimientos"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="#layout/row_establecimiento" />
Fragment.java
val cvGoBackEstablecimientos = binding!!.cvGoBackEstablecimientos
val rvEstablecimientos = binding!!.rvEstablecimientos
val adapter = EstablecimientosAdapter()
rvEstablecimientos.setHasFixedSize(true)
rvEstablecimientos.adapter = adapter
cvGoBackEstablecimientos.setOnClickListener { requireActivity().onBackPressed() }
viewModel?.getNearFreeEstablecimientos(2.0, 2.0)
?.observe(viewLifecycleOwner) { t -> adapter.addMoreEstablecimientos(t!!) }
It seems that I had some problems with the layout, I removed a CoordinatorLayout and it works now.

Strange behaviour happen in onBindViewHolder android kotlin

Hey I am working in android kotlin. I am working in reyclerview. I want to do single selection in my items. I tried some code which is working fine.
OptionsViewAdapter.kt
class OptionsViewAdapter : ListAdapter<ProductVariant, OptionsViewHolder>(PRODUCT_COMPARATOR) {
private var selectedItemPosition: Int = 0
companion object {
private val PRODUCT_COMPARATOR = object : DiffUtil.ItemCallback<ProductVariant>() {
override fun areItemsTheSame(
oldItem: ProductVariant,
newItem: ProductVariant
): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(
oldItem: ProductVariant,
newItem: ProductVariant
): Boolean {
return oldItem == newItem
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OptionsViewHolder {
return OptionsViewHolder.bindView(parent)
}
override fun onBindViewHolder(holder: OptionsViewHolder, position: Int) {
holder.binding.root.setOnClickListener {
selectedItemPosition = holder.bindingAdapterPosition
notifyAdapter()
}
val drawableColor = if (selectedItemPosition == position)
R.drawable.options_item_selected_background
else
R.drawable.options_item_default_background
holder.binding.root.background =
ContextCompat.getDrawable(holder.binding.root.context, drawableColor)
holder.bindItem(getItem(position), position)
}
fun notifyAdapter() {
notifyDataSetChanged()
}
}
OptionsViewHolder.kt
class OptionsViewHolder(
val binding: OptionsItemLayoutBinding,
) : RecyclerView.ViewHolder(binding.root) {
companion object {
fun bindView(parent: ViewGroup): OptionsViewHolder {
return OptionsViewHolder(
OptionsItemLayoutBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
}
fun bindItem(item: ProductVariant?, position: Int) {
}
}
Video for single click is working fine.
When I move onBindViewHolder code inside bindItem it not working. Can someone guide me why this is happening.
vs
OptionsViewAdapter.kt
class OptionsViewAdapter : ListAdapter<ProductVariant, OptionsViewHolder>(PRODUCT_COMPARATOR) {
companion object {
private val PRODUCT_COMPARATOR = object : DiffUtil.ItemCallback<ProductVariant>() {
override fun areItemsTheSame(
oldItem: ProductVariant,
newItem: ProductVariant
): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(
oldItem: ProductVariant,
newItem: ProductVariant
): Boolean {
return oldItem == newItem
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OptionsViewHolder {
return OptionsViewHolder.bindView(parent)
}
override fun onBindViewHolder(holder: OptionsViewHolder, position: Int) {
holder.bindItem(getItem(position), position ,::notifyAdapter)
}
fun notifyAdapter() {
notifyDataSetChanged()
}
}
OptionsViewHolder.kt
class OptionsViewHolder(
val binding: OptionsItemLayoutBinding,
) : RecyclerView.ViewHolder(binding.root) {
private var selectedItemPosition: Int = 0
companion object {
fun bindView(parent: ViewGroup): OptionsViewHolder {
return OptionsViewHolder(
OptionsItemLayoutBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
}
fun bindItem(
item: ProductVariant?,
position: Int,
onAdapterChange: () -> Unit
) {
binding.root.setOnClickListener {
selectedItemPosition = position
onAdapterChange()
}
val drawableColor = if (selectedItemPosition == position)
R.drawable.options_item_selected_background
else
R.drawable.options_item_default_background
binding.root.background =
ContextCompat.getDrawable(binding.root.context, drawableColor)
}
}
The video for single click is not working.
You moved the selectedItemPosition into the ViewHolder class, so you have a separate copy of this property for every instance of the ViewHolder class so you are no longer affecting other items in the list when any one list item is clicked.
This would be much easier to implement by making the view holder class an inner class of the Adapter so it can directly modify the adapter’s selectedItemPosition property. And I would give the property a custom setter so you can automatically notify the adapter of the change instead of having to work with a separate function call. You can also make it notify the adapter specifically of which two row items changed instead of the whole data set (more efficient and by doing it in the property setter you have access to the old and new row positions in one place easily—field and value).
private var selectedItemPosition: Int = 0
set(value) {
val oldPos = field
field = value
notifyItemChanged(oldPos)
notifyItemChanged(value)
}
Even though you are passing the method reference notifyAdapter() in bindItem() function you are not calling it in the OnClickListener that is why it is not working.

RecyclerView only displaying data after restarting Activity

So i have this strange behaviour where my RecyclerView only Displays data when i start the App and then restart the activity via Android Studio. Or make a change in XML, then undo it and restart.
The then displayed data is correct and also updates when i add things, but it is not visible after starting the app.
Can anyone help me out? I am really clueless why that would be.
Fragment:
#AndroidEntryPoint
class HistoryFragment : Fragment(R.layout.fragment_history) {
private val viewModel: PurchaseViewmodel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentHistoryBinding.bind(view)
val exampleAdapter = ExampleAdapter()
binding.apply{
recyclerView.apply{
layoutManager = LinearLayoutManager(requireContext())
adapter = exampleAdapter
setHasFixedSize(true)
}
ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return false /// We dont need any interaction with Drag&Drop we only want swipe left&right
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val receipt = exampleAdapter.currentList[viewHolder.adapterPosition]
viewModel.onSwipe(receipt)
}
}).attachToRecyclerView(recyclerView)
}
setFragmentResultListener("add_receipt_request"){_,bundle ->
val result = bundle.getInt("add_receipt_request")
viewModel.onAddResult(result)
}
viewModel.receipts.observe(viewLifecycleOwner){ /// New Items get passed to the List
exampleAdapter.submitList(it)
}
viewLifecycleOwner.lifecycleScope.launchWhenStarted { //as soon as we close our app the events will be suspended, but not deleted and will remain after restart
viewModel.addTaskEvent.collect { event->
when(event){
is PurchaseViewmodel.TasksEvent.ShowUndoDelete -> {
Snackbar.make(requireView(),"Tasks deleted", Snackbar.LENGTH_LONG)
.setAction("UNDO"){
viewModel.unDoDeleteClick(event.receipts)
}.show()
}
}
}
}
}
}
Adapter:
class ExampleAdapter : ListAdapter<Receipts,ExampleAdapter.ExampleViewHolder>(DiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
val binding = ReceiptsBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return ExampleViewHolder(binding)
}
override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
val currentItem = getItem(position)
holder.bind(currentItem)
}
override fun getItemCount(): Int {
return super.getItemCount()
}
class ExampleViewHolder(private val binding: ReceiptsBinding) : RecyclerView.ViewHolder(binding.root){ //Examples One Row in our list
fun bind (receipts: Receipts) {
binding.apply {
storeHistory.text = receipts.store
amountHistory.text = receipts.total
dateHistory.text = receipts.date
}
}
}
class DiffCallback : DiffUtil.ItemCallback<Receipts>() {
override fun areItemsTheSame(oldItem: Receipts, newItem: Receipts) =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Receipts, newItem: Receipts) =
oldItem == newItem
}
}
You should compare corresponding fields of old/new Receipts in areContentsTheSame() instead of comparing the entire old/new objects
override fun areContentsTheSame(oldItem: Receipts, newItem: Receipts) =
oldItem.store == newItem.store
&& oldItem.total == newItem.total
&& oldItem.date == newItem.date

How can I get the position of a item in ListAdapter of Android?

I use ListAdapter as the source of a RecyclerView, it will display a list of MVoice. You can see Code B.
I think I can get the position of a MVoice in ListAdapter, so I can scroll to the position of the item in RecyclerView, just like Code A
Is there a way to get the position of a Movice?
Code A
binding.recyclerViewVoice.adapter = myAdapter
mHomeViewModel.listVoiceBySort.observe(this.viewLifecycleOwner) {
myAdapter.submitList(it)
}
//val position=myAdapter.getPostionByItem(aMovice)
//binding.recyclerViewVoice.scrollToPosition(position)
Code B
class VoiceAdapters (private val aHomeViewModel: HomeViewModel, private val mPlay: PlayInterface):
ListAdapter<MVoice, VoiceAdapters.VoiceViewHolder>(MVoiceDiffCallback()) {
private lateinit var mContext: Context
private lateinit var mLifecycleOwner:LifecycleOwner
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VoiceViewHolder {
mContext = parent.context
mLifecycleOwner = mContext as LifecycleOwner
return VoiceViewHolder(
LayoutVoiceItemBinding.inflate(LayoutInflater.from(parent.context), parent, false).also {
it.lifecycleOwner = mLifecycleOwner
it.aHomeViewModel = aHomeViewModel
}
)
}
override fun onBindViewHolder(holder: VoiceViewHolder, position: Int) {
val inputMVoice = getItem(position)
holder.bind(inputMVoice)
}
inner class VoiceViewHolder (private val binding: LayoutVoiceItemBinding):
RecyclerView.ViewHolder(binding.root) {
fun bind(inputMVoice: MVoice) {
binding.amVoice = inputMVoice
binding.executePendingBindings()
}
}
}
class MVoiceDiffCallback : DiffUtil.ItemCallback<MVoice>() {
override fun areItemsTheSame(oldItem: MVoice, newItem: MVoice): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: MVoice, newItem: MVoice): Boolean {
return oldItem == newItem
}
}
You can get a reference to the list currently displayed with currentList, and use indexOf() to get the position
fun getPositionByItem(aMovice: MVoice) = currentList.indexOf(aMovice)
Add a ItemClick Listener in fun bind(), then pass the MVoice.getPosition in Toast.
Thus you would able to see the position of item in your toast.

nested recyclerview using paging adapter (paging 3) show wrong image after scrolling

How to solve the child adapter image that changes and show wrong images after scrolling?
this is my code
Parent Data Class
data class Review(
val author: String,
val date: String,
val rating: Float,
val comment: String,
val images: List<Image>)
Child Data Class
For author and comment, I only take it from the parent data class
data class Image(
var author: String? = null,
var comment: String? = null,
val large: String,
val thumbnail: String)
ParentAdapter
class ReviewAdapter(private val callback: ProductReviewImageAdapterCallback) :
PagingDataAdapter<Review, ReviewAdapter.ListViewHolder>(DIFF_CALLBACK) {
private val viewPool = RecyclerView.RecycledViewPool()
private val imageAdapter: ProductReviewImageAdapter by lazy {
ProductReviewImageAdapter(callback)
}
companion object {
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Review>() {
override fun areItemsTheSame(oldItem: Review, newItem: Review): Boolean {
return oldItem.author == newItem.author
}
override fun areContentsTheSame(oldItem: Review, newItem: Review): Boolean {
return oldItem.comment == newItem.comment
}
}
}
inner class ListViewHolder(itemBinding: ItemProductReviewBinding) :
RecyclerView.ViewHolder(itemBinding.root) {
val binding = ItemProductReviewBinding.bind(itemBinding.root)
fun bind(data: Review, position: Int) {
with(binding) {
if (data.images.isEmpty()) {
rvImageReview.gone()
} else {
setupImagesRecyclerView(rvImageReview)
rvImageReview.visible()
imageAdapter.differ.submitList(data.images)
}
tvNameReviewer.text = data.author
tvReviewDesc.text = data.comment
tvDateReview.text = data.date
ratingBarReview.rating = data.rating
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder =
ListViewHolder(
ItemProductReviewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
)
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
val review = getItem(position)
if (review != null) {
holder.bind(review, position)
}
}
private fun setupImagesRecyclerView(recyclerView: RecyclerView) {
recyclerView.apply {
layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
adapter = imageAdapter
setRecycledViewPool(viewPool)
setItemViewCacheSize(20)
}
}
}
ChildAdapter
class ProductReviewImageAdapter(private val callback: ProductReviewImageAdapterCallback) : RecyclerView.Adapter<ProductReviewImageAdapter.ListViewHolder>() {
private val diffCallback = object : DiffUtil.ItemCallback<Image>() {
override fun areItemsTheSame(
oldItem: Image,
newItem: Image
): Boolean {
return oldItem.author == newItem.author
}
override fun areContentsTheSame(
oldItem: Image,
newItem: Image
): Boolean {
return oldItem.comment == newItem.comment
}
}
val differ = AsyncListDiffer(this, diffCallback)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder =
ListViewHolder(
ItemImageBinding.inflate(LayoutInflater.from(parent.context), parent, false)
)
override fun getItemCount(): Int = differ.currentList.size
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
holder.bind(differ.currentList[position], position)
}
inner class ListViewHolder(itemBinding: ItemImageBinding) :
RecyclerView.ViewHolder(itemBinding.root) {
private val itemBinding = ItemImageBinding.bind(itemBinding.root)
fun bind(data: Image, position: Int) {
with(itemBinding) {
image.loadImageRoundedCorner(data.thumbnail)
image.setOnClickListener {
callback.onProductReviewImageClicked(position, differ.currentList)
}
}
}
}
}
Before scrolling
on first load, the first position data displays the appropriate image
before scrolling
After a bit scrolling
the image in the first position data changes to the image in the next data
after a bit scrolling
Scroll to last data/page
the last image shows an unsuitable image
scroll to last data/page
*Note
there is only 5 data, and only first and last data contains image
The image in the first position data should be a person image and the last position image should be a pink image
I use Coil as the image loader and have used the ImageView.clear() method before loading the image
Thanks in advance, sorry if my english is bad. I'm not a native speaker
Update
Fixed :
it turned out that it was only wrong at the time of adapter initialization, the adapter should be initialized in onBindViewHolder, not in the parent adapter so that not all items have the same adapter which causes all data to change

Categories

Resources