How to update RecyclerView positions after deleting? - android

I Have Recycler view with its adapter and holder. Each element has "delete" button, which has to update recyclerview. But after deleting first element, when I'm trying to delete others, from datasource are removing items with old indices of items, which I want to delete
Hope, I can explain it with an example:
Old data: (1 2 3 4 5 6 7) -> deleting "1" -> (2 3 4 5 6 7) -> deleting "2" -> (2 4 5 6 7) -> deleting "2" -> (2 5 6 7)
Here is ViewHolder source code:
inner class ViewHolder(binding: RecyclerItemBinding) : RecyclerView.ViewHolder(binding.root) {
val idView: TextView = binding.itemNumber
val contentView: Button = binding.deleteButton
init {
contentView.setOnClickListener {
removeAt(adapterPosition)
}
}
private fun removeAt(position: Int) {
values.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, itemCount)
Log.d(TAG, "remove $position left $itemCount")
}
override fun toString(): String {
return super.toString() + " '" + contentView.text + "'"
}
}
Content code:
object PlaceholderContent {
/**
* An array of sample (placeholder) items.
*/
val ITEMS: MutableList<PlaceholderItem> = ArrayList()
/**
* A map of sample (placeholder) items, by ID.
*/
private val ITEM_MAP: MutableMap<Int, PlaceholderItem> = HashMap()
private val deletedNumbers : Queue<Int> = LinkedList()
private const val INITIAL_COUNT = 15
private var biggest: Int
init {
// Add some sample items.
for (i in 1..INITIAL_COUNT) {
addItem(createPlaceholderItem(i))
}
biggest = ITEMS.last().id
}
fun size() : Int = ITEMS.size
fun addNext() {
addItem(createPlaceholderItem(deletedNumbers.poll() ?: ++biggest))
Log.d(TAG, "add $biggest")
}
fun removeAt(position: Int) {
val toRemove = ITEMS.removeAt(position)
if (toRemove.id == biggest) {
biggest--
}
deletedNumbers.add(toRemove.content.toInt())
}
private fun addItem(item: PlaceholderItem) {
ITEMS.add(item)
ITEM_MAP[item.id] = item
}
private fun createPlaceholderItem(position: Int): PlaceholderItem {
return PlaceholderItem(size(), "$position")
}
/**
* A placeholder item representing a piece of content.
*/
data class PlaceholderItem(val id: Int, val content: String): Comparable<PlaceholderItem> {
override fun toString(): String = content
override fun compareTo(other: PlaceholderItem): Int = this.id.compareTo(other.id)
}
private const val TAG = "PLACEHOLDER_CONTENT"
}

To remove a specific positioned value, I just called the getAdapterPosition() to specify the item position to be removed. Simply try this in your onBindViewHolder with the arrayList that is using like Old data: (1 2 3 4 5 6 7).
override fun onBindViewHolder(holder: RecyclerViewAdapter.ViewHolder, position: Int) {
holder.buttonDelete2.setOnClickListener {
arrayList.removeAt(holder.adapterPosition)
notifyItemRemoved(holder.adapterPosition)
}
}

Add increment in adapterPosition by 1
adapterPosition + 1
Alternatively for performance-wise, you can use DiffUtil class which will help calculates the item position change.
you can check some tutorials here:
https://blog.mindorks.com/the-powerful-tool-diff-util-in-recyclerview-android-tutorial

Related

Recycler View shows identical items

I have an arrayList<> of strings and I added 10 strings to it.
private val names: ArrayList<String> = arrayListOf()
These are the strings added
[G.I. Joe: The Rise of Cobra, Creed 2, The Equalizer 2, Ride Along 2, Mission Impossible, Mission Impossible II, Mission Impossible III, Mission Impossible: Ghost Protocol, Mission Impossible: Fallout, Suicide Squad]
I have a recycler view with its adapter as follows:
class MovieSeriesAdapter(
private val movie: MoviesInSeries,
private val movieNameList: ArrayList<String>?,
private val restMoviesPosition: Int,
): RecyclerView.Adapter<MovieSeriesAdapter.ViewHolder>() {
class ViewHolder(binding: SeriesMoviesItemBinding): RecyclerView.ViewHolder(binding.root) {
val mainThing = binding.mainThing
val tvMovieNameAndYear = binding.seriesMovieNameAndYear
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(SeriesMoviesItemBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}
#SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (position % 2 != 0) {
holder.mainThing.setBackgroundColor(Color.parseColor("#E8E8E8"))
}
val RestMoviesList = Constants.getRestOfSeriesMovies()
var targetPosition: Int = 0
when (movie.originalMovieName) {
"G.I. Joe: Retaliation" -> targetPosition = 0
"Creed" -> targetPosition = 1
"The Equalizer" -> targetPosition = 2
"Ride Along" -> targetPosition = 3
"Mission Impossible" -> targetPosition = 4
"Suicide Squad" -> targetPosition = 9
"Venom" -> targetPosition = 10
}
val targetMovieName = movieNameList!![targetPosition]
holder.tvMovieNameAndYear.text = "$targetMovieName ($targetMovieDate)"
}
override fun getItemCount(): Int {
return 5
}
The thing is that sometimes I need the recycler view to show 5 items, as in the case below. For Example, I have 5 movies of mission impossible and I want to show them. But the targetPosition is an integer variable of only one number.
I tried creating an array list of only the mission impossible movies but it showed identical 5 items with all of the data in one item.
How do I make it that when I need 5 items to be displayed, each item should get a diffent value from the name array list.
I'll recommend you to directly use the value of position for targetValue, inside onBindViewHolder while setting the value of text.
You should just give the adapter a list of the 5 you want to show.
Also, a lot of the code you wrote doesn't make a lot of sense.
For example
when (movie.originalMovieName) {
You decide here something based on movie.originalMovieName, but this movie is passed in the constructor of the adapter, which already doesn't make sense, but it also means that it will be the same movie for every item.

Android: Paging3: Duplicates items

Problem:
I get 40 items at the beginning of the list, then it starts to count from 11, and after this, everything is good. So, 1...40,11,12,13,...,300.
And when I scroll a lot to the bottom and then scroll up to see first items, the items have been changed to 1,2,...,10,1,2,...,10,1,2,...,10,11,12,...,300.
But, when I pass false to enablePlaceholders in the PagingConfig, when I scroll to the bottom, I see the issue as I said above(1,2,..,40,11,...,300) and suddenly the 40 items vanish and I only see 1,2,...,10 + 11,12,...,300(the correct way); And it doesn't change or get worse again.
ProductsPagingSource:
#Singleton
class ProductsPagingSource #Inject constructor(
private val productsApi: ProductsApi
//private val query: String
) : RxPagingSource<Int, RecyclerItem>() {
override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, RecyclerItem>> {
val position = params.key ?: STARTING_PAGE_INDEX
//val apiQuery = query
return productsApi.getBeersList(position, params.loadSize)
.subscribeOn(Schedulers.io())
.map { listBeerResponse ->
listBeerResponse.map { beerResponse ->
beerResponse.toDomain()
}
}
.map { toLoadResult(it, position) }
.onErrorReturn { LoadResult.Error(it) }
}
private fun toLoadResult(
#NonNull response: List<RecyclerItem>,
position: Int
): LoadResult<Int, RecyclerItem> {
return LoadResult.Page(
data = response,
prevKey = if (position == STARTING_PAGE_INDEX) null else position - 1,
nextKey = if (response.isEmpty()) null else position + 1,
itemsBefore = LoadResult.Page.COUNT_UNDEFINED,
itemsAfter = LoadResult.Page.COUNT_UNDEFINED
)
}
}
ProductsListRepositoryImpl:
#Singleton
class ProductsListRepositoryImpl #Inject constructor(
private val pagingSource: ProductsPagingSource
) : ProductsListRepository {
override fun getBeers(ids: String): Flowable<PagingData<RecyclerItem>> = Pager(
config = PagingConfig(
pageSize = 10,
enablePlaceholders = true,
maxSize = 30,
prefetchDistance = 5,
initialLoadSize = 40
),
pagingSourceFactory = { pagingSource }
).flowable
}
ProductsListViewModel:
class ProductsListViewModel #ViewModelInject constructor(
private val getBeersUseCase: GetBeersUseCase
) : BaseViewModel() {
private val _ldProductsList: MutableLiveData<PagingData<RecyclerItem>> = MutableLiveData()
val ldProductsList: LiveData<PagingData<RecyclerItem>> = _ldProductsList
init {
loading(true)
getProducts("")
}
private fun getProducts(ids: String) {
loading(false)
getBeersUseCase(GetBeersParams(ids = ids))
.cachedIn(viewModelScope)
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
_ldProductsList.value = it
}.addTo(compositeDisposable)
}
}
ProductsListFragment:
#AndroidEntryPoint
class ProductsListFragment : Fragment(R.layout.fragment_product_list) {
private val productsListViewModel: ProductsListViewModel by viewModels()
private val productsListAdapter: ProductsListAdapter by lazy {
ProductsListAdapter(::navigateToProductDetail)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecycler()
setupViewModel()
}
private fun setupRecycler() {
itemErrorContainer.gone()
productListRecyclerView.adapter = productsListAdapter
}
private fun setupViewModel() {
productsListViewModel.run {
observe(ldProductsList, ::addProductsList)
observe(ldLoading, ::loadingUI)
observe(ldFailure, ::handleFailure)
}
}
private fun addProductsList(productsList: PagingData<RecyclerItem>) {
loadingUI(false)
productListRecyclerView.visible()
productsListAdapter.submitData(lifecycle, productsList)
}
...
BASE_DIFF_CALLBACK:
val BASE_DIFF_CALLBACK = object : DiffUtil.ItemCallback<RecyclerItem>() {
override fun areItemsTheSame(oldItem: RecyclerItem, newItem: RecyclerItem): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: RecyclerItem, newItem: RecyclerItem): Boolean {
return oldItem == newItem
}
}
BasePagedListAdapter:
abstract class BasePagedListAdapter(
vararg types: Cell<RecyclerItem>,
private val onItemClick: (RecyclerItem, ImageView) -> Unit
) : PagingDataAdapter<RecyclerItem, RecyclerView.ViewHolder>(BASE_DIFF_CALLBACK) {
private val cellTypes: CellTypes<RecyclerItem> = CellTypes(*types)
override fun getItemViewType(position: Int): Int {
getItem(position).let {
return cellTypes.of(it).type()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return cellTypes.of(viewType).holder(parent)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
getItem(position).let {
cellTypes.of(it).bind(holder, it, onItemClick)
}
}
}
I had to set the same number for pageSize and initialLoadSize. Also, I had to set the enablePlaceholders to false.
config = PagingConfig(
pageSize = 10,
enablePlaceholders = false,
maxSize = 30,
prefetchDistance = 5,
initialLoadSize = 10
),
But still, I want to know if it's the normal way? If yes, I couldn't find anywhere point to this! If not, why's that? Why initialLoadSize can not have value more than the pageSize?!
As we can see, the default value for the initialLoadSize is:
internal const val DEFAULT_INITIAL_PAGE_MULTIPLIER = 3
val initialLoadSize: Int = pageSize * DEFAULT_INITIAL_PAGE_MULTIPLIER,
Your issue is most likely because at the repository layer your results page numbers are indexed with numbers derived from the total divided by your page size.
This page number scheme assumes that you will page through the items with pages of the same size. However, Paging wants to get an initial page that's three times bigger by default, and then each page should be the page size.
So, the indexes might be like 0 through totalElements/PageSize, with the number for page that includes a given position equaling itemsIndex/PageSize.
This part is especially relevant:
return LoadResult.Page(
data = response,
prevKey = if (position == STARTING_PAGE_INDEX) null else position - 1,
nextKey = if (response.isEmpty()) null else position + 1,
itemsBefore = LoadResult.Page.COUNT_UNDEFINED,
itemsAfter = LoadResult.Page.COUNT_UNDEFINED
)
Let's imagine a pagesize of 10, an initial load of 30, and 100 elements total. We start with page 0, and we request 30 items. Position is 0, and params.loadSize is 30.
productsApi.getBeersList(0, 30)
Then we return a page object with those 30 elements and a nextPage key of 1.
If we imagine all our objects as list, the first page would be the asterisks in this span: [***-------]
Let's get the next page:
productsApi.getBeersList(1, 10)
That returns elements that are this from our span: [-*--------]
And then you get: [--*-------]
So the 0th page is fine, but the 1th and 2nd page overlap with it. Then, pages 3 and onward contain new elements.
Because you're getting the keys for the next and previous pages by adding or subtracting to get the adjacent keys to the current page of the current length, the index can't scale with the page size. This isn't always easy without knowing what is inside the PagingConfig.
However you can make it work with dynamic page sizes if you can guarantee your initial load size is your regular page size times some integer and that you'll always get the requested number of items except for the last page, you could store an offset as your next/previous page keys, and turn that offset into the next page at load like:
/* Value for api pageNo */
val pageNo = (params.key/params.loadSize + STARTING_PAGE_INDEX) ?: STARTING_PAGE_INDEX
productsApi.getBeersList(pageNo, params.loadSize) // and so on
/* for offset keys in PageData */
nextKey = (pageNo + 1) * loadSize
prevKey = (pageNo - 1) * loadSize // Integer division rounds down so larger windows start where they should

RecyclerView duplicates data multiple times

I'm developing a timetable application and I have a fragment in it, which displays the users subjects and lessons in a RecyclerView, like this:
It works fine, but only for the first time. The moment I open the fragment for the second time (or just simply reload it) I get this weird bug: It starts filling in random circles with that blue-ish color as if there were lessons on that particular day. For example.: Let's say the user added two subjects, Calculus I and Databases, and a lesson to Databases on Wednesday. As soon as the fragment gets opened for the second time, there'll be a filled-in circle next to Calculus I's Wednesday as well.
I think there must be a problem somewhere in the SubjectsViewHolder class, but just in case I missed something, here's the whole RecyclerView's adapter file:
// Each constant value represents a view type
private const val VIEW_TYPE_NOT_EMPTY = 0
private const val VIEW_TYPE_EMPTY = 1
/**
* A [RecyclerView.Adapter] subclass.
* This class serves as an adapter for RecyclerViews
* which were created to display lessons.
*
* #property subjectsList An [ArrayList] containing all [Subject] objects to display
* #property lessonsList An [ArrayList] containing lessons of subjects
* #property listener Fragments that use this class must implement [OnSubjectClickListener]
*/
class SubjectsRecyclerViewAdapter(
private var subjectsList: ArrayList<Subject>?,
private var lessonsList: ArrayList<Lesson>?,
private val listener: OnSubjectClickListener
) : RecyclerView.Adapter<SubjectsRecyclerViewAdapter.ViewHolder>() {
/**
* This interface must be implemented by activities/fragments that contain
* this RecyclerViewAdapter to allow an interaction in this class to be
* communicated to the activity/fragment.
*/
interface OnSubjectClickListener {
fun onSubjectClick(subject: Subject)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return when (viewType) {
VIEW_TYPE_EMPTY -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.no_subject_list_item, parent, false)
EmptySubjectViewHolder(view)
}
VIEW_TYPE_NOT_EMPTY -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.subject_list_items, parent, false)
SubjectViewHolder(view)
}
else -> throw IllegalStateException("Couldn't recognise the view type")
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val list = subjectsList
val lessonsList = lessonsList
when (getItemViewType(position)) {
VIEW_TYPE_EMPTY -> {
// We are not putting any data into the empty view, therefore we do not need to do anything here
}
VIEW_TYPE_NOT_EMPTY -> {
if (list != null && lessonsList != null) {
val subject = list[position]
val days = arrayListOf<Int>()
for (lesson in lessonsList) {
if (lesson.subjectId == subject.id) {
days.add(lesson.day)
}
}
holder.bind(subject, days, listener)
}
}
}
}
override fun getItemCount(): Int {
val list = subjectsList
return if (list == null || list.size == 0) 1 else list.size
}
override fun getItemViewType(position: Int): Int {
val list = subjectsList
return if (list == null || list.size == 0) VIEW_TYPE_EMPTY else VIEW_TYPE_NOT_EMPTY
}
/**
* Swap in a new [ArrayList], containing [Subject] objects
*
* #param newList New list containing subjects
* #return Returns the previously used list, or null if there wasn't one
*/
fun swapSubjectsList(newList: ArrayList<Subject>?): ArrayList<Subject>? {
if (newList === subjectsList) {
return null
}
val numItems = itemCount
val oldList = subjectsList
subjectsList = newList
if (newList != null) {
//notify the observers
notifyDataSetChanged()
} else {
//notify the observers about the lack of a data set
notifyItemRangeRemoved(0, numItems)
}
return oldList
}
/**
* Swap in a new [ArrayList], containing [Lesson] objects
*
* #param newList New list containing lessons
* #return Returns the previously set list, or null if there wasn't one
*/
fun swapLessonsList(newList: ArrayList<Lesson>?): ArrayList<Lesson>? {
if (newList === lessonsList) {
return null
}
val list = lessonsList
val numItems = if (list == null || list.size == 0) 0 else list.size
val oldList = lessonsList
lessonsList = newList
if (newList != null) {
notifyDataSetChanged()
} else {
//notify the observers about the lack of a data set
notifyItemRangeRemoved(0, numItems)
}
return oldList
}
open class ViewHolder(override val containerView: View) :
RecyclerView.ViewHolder(containerView), LayoutContainer {
open fun bind(
subject: Subject,
days: ArrayList<Int>,
listener: OnSubjectClickListener
) {
}
}
private class SubjectViewHolder(override val containerView: View) : ViewHolder(containerView) {
override fun bind(
subject: Subject,
days: ArrayList<Int>,
listener: OnSubjectClickListener
) {
containerView.sli_name.text = subject.name
for (day in days) {
when (day) {
1 -> {
containerView.sli_sunday.setBackgroundResource(R.drawable.has_lesson_on_day)
containerView.sli_sunday.setTextColor(
ContextCompat.getColor(
containerView.context,
R.color.colorBackgroundPrimary
)
)
}
2 -> {
containerView.sli_monday.setBackgroundResource(R.drawable.has_lesson_on_day)
containerView.sli_monday.setTextColor(
ContextCompat.getColor(
containerView.context,
R.color.colorBackgroundPrimary
)
)
}
3 -> {
containerView.sli_tuesday.setBackgroundResource(R.drawable.has_lesson_on_day)
containerView.sli_tuesday.setTextColor(
ContextCompat.getColor(
containerView.context,
R.color.colorBackgroundPrimary
)
)
}
4 -> {
containerView.sli_wednesday.setBackgroundResource(R.drawable.has_lesson_on_day)
containerView.sli_wednesday.setTextColor(
ContextCompat.getColor(
containerView.context,
R.color.colorBackgroundPrimary
)
)
}
5 -> {
containerView.sli_thursday.setBackgroundResource(R.drawable.has_lesson_on_day)
containerView.sli_thursday.setTextColor(
ContextCompat.getColor(
containerView.context,
R.color.colorBackgroundPrimary
)
)
}
6 -> {
containerView.sli_friday.setBackgroundResource(R.drawable.has_lesson_on_day)
containerView.sli_friday.setTextColor(
ContextCompat.getColor(
containerView.context,
R.color.colorBackgroundPrimary
)
)
}
7 -> {
containerView.sli_saturday.setBackgroundResource(R.drawable.has_lesson_on_day)
containerView.sli_saturday.setTextColor(
ContextCompat.getColor(
containerView.context,
R.color.colorBackgroundPrimary
)
)
}
}
}
containerView.sli_linearlayout.setOnClickListener {
listener.onSubjectClick(subject)
}
}
}
// We do not need to override the bind method since we're not putting any data into the empty view
private class EmptySubjectViewHolder(override val containerView: View) :
ViewHolder(containerView)
}
It is seem to be Recycler Views are not getting cleaned before reuse them.
you must clear/reset your days color.. e.g here
containerView.sli_name.text = subject.name
<HERE CLEAR/RESET YOUR DAYS COLOR FOR ALL THE 7 DAYS>
for (day in days) {
when (day) { ... }
I think you have to use database here if user enter two subjects you have to save local database next time he opens fragment he can see saved subjects

Android how to interact with nested recyclerView from fragment

How does one properly send data to child adapter in a fragment?
I'm basically trying to implement an Instagram like comments-section, e.g. a bunch of comments that can each have more comments (replies).
To do that, I use one main recyclerView + main adapter, which instances are retained in my fragment, and within the main adapter I bind the children comments (recyclerView + adapter).
Adding comments to the main adapter is easy since the object is always available in the fragment, so I just call mainAdapter.addComments(newComments):
MainAdapter
fun addComments(newComments: List<Comment>){
comments.addAll( 0, newComments) //loading comments or previous comments go to the beginning
notifyItemRangeInserted(0, newComments.size)
}
But how to call addComments of one particular nested-rV? I read I should not save the adapter instances and only use positions.
I'm trying to do that in my Fragment as follows:
val item = rVComments.findViewHolderForItemId(mAdapter.itemId)!!.itemView
val adapt = item.rVReplies.adapter as ChildCommentsAdapter
adapt.addComment(it.data.comment)
But that doesn't work very well: since we have only RecyclerViews, that particular ViewHolder is often already recycled if the user scrolled after posting or fetching items, which leads to a NullPointerException.
Hence the initial question: how does one properly interact with nested recyclerviews and their adapter? If the answer is via Interface, please provide an example as I've tried it without success since I shouldn't save adapter objects.
You can achieve that using a single multi-view type adapter by placing the comments
as part of the parent item, with that, you add the child items below the parent item and call notifyItemRangeInserted.
That way you don't have to deal with most of the recycling issues.
When you want to update a comment you just update the comment inside the parent item and call notifyItemChanged.
If you want I created a library that can generate that code for you in compile time.
It supports the exact case you wanted and much more.
Using #Gil Goldzweig's suggestion, here is what I did: in case of an Instagram like comments' system with replies, I did use a nested recyclerView system. It just makes it easier to add and remove items. However, as for the question How does one properly send data to child adapter in a fragment? You don't. It gets super messy. From my fragment, I sent the data to my mainAdapter, which in turn sent the data to the relevant childAdapter. The key to make it smooth is using notifyItemRangeInserted when adding a comment to the mainAdapter and then notifyItemChanged when adding replies to a comment. The second event will allow sending data to the child adapter using the payload. Here's the code in case other people are interested:
Fragment
class CommentsFragment : androidx.fragment.app.Fragment(), Injectable,
SendCommentButton.OnSendClickListener, CommentsAdapter.Listener {
#Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val viewModel by lazy {
ViewModelProviders.of(requireActivity(), viewModelFactory).get(CommentsViewModel::class.java)
}
private val searchViewModel by lazy {
ViewModelProviders.of(requireActivity(), viewModelFactory).get(SearchViewModel::class.java)
}
private val mAdapter = CommentsAdapter(this)
private var contentid: Int = 0 //store the contentid to process further posts or requests for more comments
private var isLoadingMoreComments: Boolean = false //used to check if we should fetch more comments
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_comments, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
//hide the action bar
activity?.findViewById<BottomNavigationView>(R.id.bottomNavView)?.visibility = View.GONE
contentid = arguments!!.getInt("contentid") //argument is mandatory, since comment is only available on content
ivBackArrow.setOnClickListener{ activity!!.onBackPressed() }
viewModel.initComments(contentid) //fetch comments
val layoutManager = LinearLayoutManager(this.context)
layoutManager.stackFromEnd = true
rVComments.layoutManager = layoutManager
mAdapter.setHasStableIds(true)
rVComments.adapter = mAdapter
setupObserver() //observe initial comments response
setupSendCommentButton()
post_comment_text.setSearchViewModel(searchViewModel)
setupScrollListener(layoutManager) //scroll listener to load more comments
iVCancelReplyTo.setOnClickListener{
//reset ReplyTo function
resetReplyLayout()
}
}
private fun loadMoreComments(){
viewModel.fetchMoreComments(contentid, mAdapter.itemCount)
setupObserver()
}
/*
1.check if not already loading
2.check scroll position 0
3.check total visible items != total recycle items
4.check itemcount to make sure we can still make request
*/
private fun setupScrollListener(layoutManager: LinearLayoutManager){
rVComments.addOnScrollListener(object: RecyclerView.OnScrollListener(){
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val visibleItemCount = rVComments.childCount
val totalItemCount = layoutManager.itemCount
val pos = layoutManager.findFirstCompletelyVisibleItemPosition()
if(!isLoadingMoreComments && pos==0 && visibleItemCount!=totalItemCount && mAdapter.itemCount%10==0){
//fetch more comments
isLoadingMoreComments = true
loadMoreComments()
}
}
})
}
private fun setupSendCommentButton() {
btnSendComment.setOnSendClickListener(this)
}
override fun onSendClickListener(v: View?) {
if(isInputValid(post_comment_text.text.toString())) {
val isReply = mAdapter.commentid!=null
viewModel.postComment(post_comment_text.text.toString(), mAdapter.commentid?: contentid, isReply) //get reply ID, otherwise contentID
observePost()
post_comment_text.setText("")
btnSendComment.setCurrentState(SendCommentButton.STATE_DONE)
}
}
override fun postCommentAsReply(username: String) {
//main adapter method to post a reply
val replyText = "${getString(R.string.replyingTo)} $username"
tVReplyTo.text = replyText
layoutReplyTo.visibility=View.VISIBLE
post_comment_text.requestFocus()
}
override fun fetchReplies(commentid: Int, commentsCount: Int) {
//main adapter method to fetch replies
if(!isLoadingMoreComments){ //load one series at a time
isLoadingMoreComments = true
viewModel.fetchReplies(commentid, commentsCount)
viewModel.replies.observe(this, Observer<Resource<List<Comment>>> {
if (it?.data != null) when (it.status) {
Resource.Status.LOADING -> {
//showProgressBar(true)
}
Resource.Status.ERROR -> {
//showProgressBar(false)
isLoadingMoreComments = false
}
Resource.Status.SUCCESS -> {
isLoadingMoreComments = false
mAdapter.addReplies(mAdapter.replyCommentPosition!!, it.data)
rVComments.scrollToPosition(mAdapter.replyCommentPosition!!)
}
}
})
}
}
private fun isInputValid(text: String): Boolean = text.isNotEmpty()
private fun observePost(){
viewModel.postComment.observe(this, Observer<Resource<PostCommentResponse>> {
if (it?.data != null) when (it.status) {
Resource.Status.LOADING -> {
//showProgressBar(true)
}
Resource.Status.ERROR -> {
//showProgressBar(false)
}
Resource.Status.SUCCESS -> {
if(it.data.asReply){
//dispatch comment to child adapter via main adapter
mAdapter.addReply(mAdapter.replyCommentPosition!!, it.data.comment)
rVComments.scrollToPosition(mAdapter.replyCommentPosition!!)
}else{
mAdapter.addComment(it.data.comment)
}
resetReplyLayout()
//showProgressBar(false)
}
}
})
}
private fun setupObserver(){
viewModel.comments.observe(this, Observer<Resource<List<Comment>>> {
if (it?.data != null) when (it.status) {
Resource.Status.LOADING -> {
//showProgressBar(true)
}
Resource.Status.ERROR -> {
isLoadingMoreComments = false
//showProgressBar(false)
}
Resource.Status.SUCCESS -> {
mAdapter.addComments(it.data)
isLoadingMoreComments = false
//showProgressBar(false)
}
}
})
}
private fun resetReplyLayout(){
layoutReplyTo.visibility=View.GONE
mAdapter.replyCommentPosition = null
mAdapter.commentid = null
}
override fun onStop() {
super.onStop()
activity?.findViewById<BottomNavigationView>(R.id.bottomNavView)?.visibility = View.VISIBLE
}
}
MainAdapter
class CommentsAdapter(private val listener: Listener) : RecyclerView.Adapter<CommentsAdapter.ViewHolder>(), ChildCommentsAdapter.ChildListener {
//method from child adapter
override fun postChildReply(replyid: Int, username: String, position: Int) {
commentid = replyid
replyCommentPosition = position
listener.postCommentAsReply(username)
}
interface Listener {
fun postCommentAsReply(username: String)
fun fetchReplies(commentid: Int, commentsCount: Int=0)
}
class ViewHolder(val view: View) : RecyclerView.ViewHolder(view)
private var comments = mutableListOf<Comment>()
private var repliesVisibility = mutableListOf<Boolean>() //used to store visibility state for replies
var replyCommentPosition: Int? = null //store the main comment's position
var commentid: Int? = null //used to indicate which comment is replied to
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_comment, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val comment = comments[position]
with(holder.view) {
//reset visibilities (rebinding purpose)
rVReplies.visibility = View.GONE
iVMoreReplies.visibility = View.GONE
tVReplies.visibility = View.GONE
content.loadUserPhoto(comment.avatarThumbnailURL)
text.setCaptionText(comment.username!!, comment.comment)
tvTimestamp.setTimeStamp(comment.timestamp!!)
val child = ChildCommentsAdapter(
//we pass parent commentid and position to child to be able to pass it again on click
this#CommentsAdapter, comments[holder.adapterPosition].id!!, holder.adapterPosition
)
val layoutManager = LinearLayoutManager(this.context)
rVReplies.layoutManager = layoutManager
rVReplies.adapter = child
//initial visibility block when binding the viewHolder
val txtMore = this.resources.getString(R.string.show_more_replies)
if(comment.repliesCount>0) {
tVReplies.visibility = View.VISIBLE
if (repliesVisibility[position]) {
//replies are to be shown directly
rVReplies.visibility = View.VISIBLE
child.addComments(comment.replies!!)
tVReplies.text = resources.getString(R.string.hide_replies)
if (comment.repliesCount > comment.replies!!.size) {
//show the load more replies arrow if we can fetch more replies
iVMoreReplies.visibility = View.VISIBLE
}
} else {
//replies all hidden
val txt = txtMore + " (${comment.repliesCount})"
tVReplies.text = txt
}
}
//second visibility block when toggling with the show more/hide textView
tVReplies.setOnClickListener{
//toggle child recyclerView visibility and change textView text
if(holder.view.rVReplies.visibility == View.GONE){
//show stuff
if(comment.replies!!.isEmpty()){
Timber.d(holder.adapterPosition.toString())
//fetch replies if none were fetched yet
replyCommentPosition = holder.adapterPosition
listener.fetchReplies(comments[holder.adapterPosition].id!!)
}else{
//load comments into adapter if not already
if(comment.replies!!.size>child.comments.size){child.addComments(comment.replies!!)}
}
repliesVisibility[position] = true
holder.view.rVReplies.visibility = View.VISIBLE
holder.view.tVReplies.text = holder.view.resources.getString(R.string.hide_replies)
if (comment.repliesCount > comment.replies!!.size && comment.replies!!.isNotEmpty()) {
//show the load more replies arrow if we can fetch more replies
iVMoreReplies.visibility = View.VISIBLE
}
}else{
//hide replies and change text
repliesVisibility[position] = false
holder.view.rVReplies.visibility = View.GONE
holder.view.iVMoreReplies.visibility = View.GONE
val txt = txtMore + " (${comment.repliesCount})"
holder.view.tVReplies.text = txt
}
}
tvReply.setOnClickListener{
replyCommentPosition = holder.adapterPosition
commentid = comments[holder.adapterPosition].id!!
listener.postCommentAsReply(comments[holder.adapterPosition].username!!)
}
iVMoreReplies.setOnClickListener{
replyCommentPosition = holder.adapterPosition
listener.fetchReplies(comments[holder.adapterPosition].id!!, layoutManager.itemCount) //pass amount of replies too
}
}
}
#Suppress("UNCHECKED_CAST")
override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
if(payloads.isNotEmpty()){
//add reply to child adapter
with(holder.view){
Timber.d(payloads.toString())
val adapter = rVReplies.adapter as ChildCommentsAdapter
if(payloads[0] is Comment){
adapter.addComment(payloads[0] as Comment)
}else{
//will be of type List<Comment>
adapter.addComments(payloads[0] as List<Comment>)
val comment = comments[position]
if (comment.repliesCount > comment.replies!!.size) {
//show the load more replies arrow if we can fetch more replies
iVMoreReplies.visibility = View.VISIBLE
}else{
iVMoreReplies.visibility = View.GONE
}
}
}
}else{
super.onBindViewHolder(holder,position, payloads) //delegate to normal binding process
}
}
override fun getItemCount(): Int = comments.size
//add multiple replies to child adapter at pos 0
fun addReplies(position: Int, newComments: List<Comment>){
comments[position].replies!!.addAll(0, newComments)
notifyItemChanged(position, newComments)
}
//add a single reply to child adapter at last position
fun addReply(position: Int, newComment: Comment){
comments[position].replies!!.add(newComment)
comments[position].repliesCount += 1 //update replies count in case viewHolder gets rebinded
notifyItemChanged(position, newComment)
}
//add a new comment to main adapter at last position
fun addComment(comment: Comment){
comments.add(comment) //new comment just made goes to the end
repliesVisibility.add(false)
notifyItemInserted(itemCount-1)
}
//add multiple new comments to main adapter at pos 0
fun addComments(newComments: List<Comment>){
comments.addAll( 0, newComments) //loading comments or previous comments go to the beginning
repliesVisibility.addAll(0, List(newComments.size) { false })
notifyItemRangeInserted(0, newComments.size)
}
}
The childAdapter is very basic and has nearly 0 logic.

RecyclerView: Inconsistency detected when update grouped items by PagedListAdapter

I using android.arch.paging.PagedListAdapter <Item, RecyclerView.ViewHolder> and Room DB as data source for show items in RecyclerView.
Each item has date day. I also group elements by this date in override fun onCurrentListChanged(currentList: PagedList<Item>?).
Grouping occurs by dividing into two lists (Items and Dates) with fake positions. Total count is sum items count and dates count.
My problem is an IndexOutOfBoundsException: Inconsistency detected from RecyclerView when refresh or load next items.
Possible solutions: 1 - refuse to separate items (not suitable for my task). 2 - Use notifyDataSetChanged() after submit items (but disappear animation and appear blink update viewHolders).
Can anyone help?
private var fakePositionDates: Map<Int, Date> = emptyMap()
private var fakePositionTaskPositions: Map<Int, Int> = emptyMap()
override fun getItemCount(): Int {
return fakePositionTaskPositions.size + fakePositionDates.size
}
override fun submitList(pagedList: PagedList<Task>?) {
super.submitList(pagedList)
}
override fun onCurrentListChanged(currentList: PagedList<Task>?) {
val groupTasksPositions = currentList?.asIterable()
?.mapIndexed { index, task ->
Pair(index, task.publishDate)
}
?.groupBy { it.second }
?.mapValues {
it.value.map { it.first }
}
?.toSortedMap(Comparator { o1, o2 ->
o2.compareTo(o1)
})
?: sortedMapOf()
val fakePositionDates = mutableMapOf<Int, Date>()
val fakePositionTaskPositions = mutableMapOf<Int, Int>()
var fakePosition = 0
groupTasksPositions.forEach { date, realPositions ->
fakePositionDates[fakePosition] = date
fakePosition += 1
realPositions.forEach {
fakePositionTaskPositions[fakePosition] = it
fakePosition += 1
}
}
this.fakePositionTaskPositions = fakePositionTaskPositions
this.fakePositionDates = fakePositionDates
}
Try to add adapter.submitList(null) and adapter.notifyDataSetChanged in your activity or fragment before you call view model function to refresh your recyclerview

Categories

Resources