Get binded ViewHolder's positions scope - android

I want to get range of 'alive' ViewHolders. There is my not working solution.
class NotesRvAdapter : RecyclerView.Adapter<NoteDateViewHolder> {
private var lastBindPosition = 0
private var lastUnbindPosition = 10
override fun onBindViewHolder(holder: NoteDateViewHolder, position: Int) {
...
onScopeChanged()
}
fun onScopeChanged() {
var maxPosition = 0
var minPosition = 0
if(lastBindPosition > lastUnbindPosition) {
maxPosition = lastBindPosition
minPosition = lastUnbindPosition
} else {
maxPosition = lastUnbindPosition
minPosition = lastBindPosition
}
scopeListener.onChanged(NotesRequest(maxPosition, minPosition))
}
override fun onViewDetachedFromWindow(holder: NoteDateViewHolder) {
lastUnbindPosition = holder.adapterPosition
super.onViewDetachedFromWindow(holder)
}
}
As onBindViewHolder(...) and onViewDetachedFromWindow(...) called in shuffled order. And it is not the only problem :)
Any ideas to get 'alive' position's scope? LayoutManager can provide only first/last visible items, not 'bound'.

Related

Why is my List not being recognized as it has been initialized in onDraw()?

I have initialized my List in the function below in MainActivitywith DataPoint(data class in GraphView)
MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var graph_view = GraphView(this)
graph_view.setData(generateRandomDataPoints())
}
fun generateRandomDataPoints(): List<GraphView.DataPoint> {
val random = Random()
return (0..20).map {
GraphView.DataPoint(it, random.nextInt(50) + 1)
}
}
}
GraphView
private val dataSet = arrayListOf<DataPoint>()
private var xMin = 0
private var xMax = 0
private var yMin = 0
private var yMax = 0
private val dataPointPaint = Paint().apply {
color = Color.BLACK
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
Log.e("D SIze", dataSet.size.toString())
for(i in 0 until dataSet.size){
val realX = dataSet[i].xVal.toRealX()
val realY = dataSet[i].yVal.toRealY()
Log.e("TAG", realX.toString())
Log.e("TAG", realY.toString())
Log.e("TAG", "NOT BEingf claeed")
canvas.drawCircle(realX, realY, 17f, dataPointPaint)
}
}
fun setData(newDataSet: List<DataPoint>) {
Log.e("TAG", newDataSet.size.toString())
xMin = newDataSet.minByOrNull { it.xVal }?.xVal ?: 0
xMax = newDataSet.maxByOrNull { it.xVal }?.xVal ?: 0
yMin = newDataSet.minByOrNull { it.yVal }?.yVal ?: 0
yMax = newDataSet.maxByOrNull { it.yVal }?.yVal ?: 0
dataSet.clear() // clear if any point are entered
dataSet.addAll(newDataSet) // add all points fro newDataSet
for(i in 0 .. dataSet.size-1){
Log.e("!!!!", dataSet[i].toString() )
}
invalidate()
}
private fun Int.toRealX() = toFloat() / xMax * width
private fun Int.toRealY() = toFloat() / yMax * height
data class DataPoint(
val xVal: Int,
val yVal: Int)
}
All of my logs work as expected and print's what is expected.
But when onDraw() is called from the invalidate() in the setData() function the log at the start returns 0. Which is why the for loop in onDraw() is never called and no points dots are being printed to the canvas?
I do not know why as all my other logs show that the data has been added for example the for loop in setData() prints
DataPoint(xVal=1, yVal=20)
DataPoint(xVal=3, yVal=37)
DataPoint(xVal=4, yVal=39)
....
Why is this and how can I solve it please?

How to add more list of data without clearing the previous in Recycler View Adapter in kotlin?

I'm trying to make a recycler view that load more data as the user scroll down without deleting the previous cell. example:(Instagram, twitter...)
when I scroll down the new data is fetched in all the recycler-view cells the previous and the new cells.
so if I have 10cells, then I scroll down, it gets another new 10 however now all 20 are the same, and the first 10 are substituted.
The Main fragment
photosList.layoutManager = mLayoutManager
viewModel.refresh()
photosList.apply {
layoutManager = LinearLayoutManager(context)
adapter = photosAdapter
}
observeViewModel()
photosList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (dy > 0) { //check for scroll down
//visibleItemCount = mLayoutManager.childCount
var layoutManager = photosList.layoutManager as LinearLayoutManager
visibleItemCount =
layoutManager.findLastVisibleItemPosition() - layoutManager.findFirstVisibleItemPosition() + 1
totalItemCount = layoutManager.itemCount
pastVisibleItems = layoutManager.findFirstVisibleItemPosition()
if (loading) {
if (visibleItemCount + pastVisibleItems >= totalItemCount) {
loading = false
// Fetch new data
viewModel.fetchMorePhotos()
observeViewModelGetMore()
loading = true
}
}
}
}
})
The ViewModel
fun fetchMorePhotos() {
pageNumber += 1
fetchPhotos()
}
private fun fetchPhotos() {
loading.value = true
//loading2.value = true
disposable.add(
PhotosService.getPhotos(pageNumber)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableSingleObserver<List<PhotoData>>() {
override fun onSuccess(value: List<PhotoData>?) {
Photos.value = value!!
PhotoLoadError.value = false
loading.value = false
//loading2.value = false
}
override fun onError(e: Throwable?) {
PhotoLoadError.value = true
loading.value = false
//loading2.value = false
}
})
)
}
The Adapter
class PhotoListAdapter(
var photos: ArrayList<PhotoData>,
private var click_listener: OnPhotoItemClickListner
) :
RecyclerView.Adapter<PhotoListAdapter.PhotoViewHolder>() {
fun updatePhotos(newPhotos: List<PhotoData>) {
photos.clear()
photos.addAll(newPhotos)
notifyDataSetChanged()
}
fun getMorePhotos(newPhotos: List<PhotoData>) {
val position: Int = photos.size + 1
photos.addAll(newPhotos)
notifyItemChanged(position,newPhotos)
}
Infinite scrolling is a complicated topic that I wouldn't try to solve yourself. You'll want to use the Android Paging library:
https://proandroiddev.com/infinite-scrolling-with-android-paging-library-and-flow-api-e017f47517d6

RecyclerView with nested setOnClickListener in a quiz based app

I have an issue with the implementation of a basic functionality of a quiz based application. Briefly, I have "questions" and "answers" in an ArrayList<Question> (each Question has its own ArrayList<Answer>, 3 for this example) that I used to populate an adapter of a RecyclerView in a fragment managed with MVVM.
This is my onBindViewHolder function:
...
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
...
val curQuest = myDataset[position]
val shuffledAnswers = curQuest.answers
holder.ans1.text = shuffledAnswers[0].answer_text
holder.ans1.setOnClickListener {
it.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.selected_ans_quiz)
holder.ans2.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.default_ans_quiz)
holder.ans3.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.default_ans_quiz)
}
holder.ans2.text = shuffledAnswers[1].answer_text
holder.ans2.setOnClickListener {
it.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.selected_ans_quiz)
holder.ans1.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.default_ans_quiz)
holder.ans3.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.default_ans_quiz)
}
holder.ans3.text = shuffledAnswers[2].answer_text
holder.ans3.setOnClickListener {
it.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.selected_ans_quiz)
holder.ans2.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.default_ans_quiz)
holder.ans1.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.default_ans_quiz)
}
}
Everything works well but the selection of the answer: if I select an answer of the first question (myDataset[0]), the view changes also for the N+0 element in the list, where N is the max chunck of items loaded by the RecyclerView
How can I set the right attributes in a RecyclerView for each sub-element without propagation after the Nth element loaded by onBindViewHolder?
Can it be fixed or should I have to change the implementation way?
EDIT: I just tried an alternative but with the same result, using an interface:
QuizAdapter.kt
...
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
...
val curQuest = myDataset[position]
val shuffledAnswers = curQuest.answers
holder.ans1.text = shuffledAnswers[0].answer_text
holder.ans1.setOnClickListener {
mCallback.onClick(shuffledAnswers[0],position,it,holder.ans2,holder.ans3)
}
holder.ans2.text = shuffledAnswers[1].answer_text
holder.ans2.setOnClickListener {
mCallback.onClick(shuffledAnswers[1],position,it,holder.ans1,holder.ans3)
}
holder.ans3.text = shuffledAnswers[2].answer_text
holder.ans3.setOnClickListener {
mCallback.onClick(shuffledAnswers[2],position,it,holder.ans2,holder.ans1)
}
interface OnItemClickListener{
fun onClick(answerSelected: Answer?, questPosition: Int, selectedItemView: View, firstItemView: View, secondItemView: View)
}
QuizFragment.kt
...
mAdapter = QuizAdapter(this)
listQuestions.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(activity)
adapter = mAdapter
itemAnimator = DefaultItemAnimator()
}
mAdapter.setOnItemClickListener(object : QuizAdapter.OnItemClickListener{
override fun onClick(answerSelected: Answer?,
questPosition: Int,
selectedItemView: View,
firstItemView: View,
secondItemView: View) {
Snackbar.make(selectedItemView, "Your answer for $questPosition is ${answerSelected!!.isCorrect}.",
Snackbar.LENGTH_SHORT)
.setAction("Action", null).show()
selectedItemView.background = ContextCompat.getDrawable(requireContext(),R.drawable.selected_ans_quiz)
firstItemView.background = ContextCompat.getDrawable(requireContext(),R.drawable.default_ans_quiz)
secondItemView.background = ContextCompat.getDrawable(requireContext(),R.drawable.default_ans_quiz)
quizViewModel.chosenAnswers[questPosition] = answerSelected
}
})
fab_endQuiz.setOnClickListener { view ->
Snackbar.make(view, quizViewModel.chosenAnswers.toString(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
//parentFragment?.findNavController()?.navigate(R.id.action_quizFragment_to_nav_home)
}
As you can see, with a FAB I can test the correctness of the selected answers and it seems ok, the map is filled with the user choices, even if there's a change in selection (map position, representing the question, is modified correctly).
But background colors remain mixed in different positions (the current ones visible in the RecyclerView plus others ahead), as said before.
If it can be useful, I found a solution.
I added a boolean value to Answer class so that the RecyclerView has to check that when builds its list in xml, mixing to what I've done before
QuizAdapter.kt
...
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
...
val curQuest = myDataset[position]
val shuffledAnswers = curQuest.answers
holder.ans1.text = shuffledAnswers[0].answer_text
if(shuffledAnswers[0].isSelected)
holder.ans1.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.selected_ans_quiz)
else
holder.ans1.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.default_ans_quiz)
holder.ans1.setOnClickListener {
shuffledAnswers[0].isSelected = true
shuffledAnswers[1].isSelected = false
shuffledAnswers[2].isSelected = false
mCallback.onClick(shuffledAnswers[0],position,it,holder.ans2,holder.ans3)
}
holder.ans2.text = shuffledAnswers[1].answer_text
if(shuffledAnswers[1].isSelected)
holder.ans2.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.selected_ans_quiz)
else
holder.ans2.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.default_ans_quiz)
holder.ans2.setOnClickListener {
shuffledAnswers[0].isSelected = false
shuffledAnswers[1].isSelected = true
shuffledAnswers[2].isSelected = false
mCallback.onClick(shuffledAnswers[1],position,it,holder.ans1,holder.ans3)
}
holder.ans3.text = shuffledAnswers[2].answer_text
if(shuffledAnswers[2].isSelected)
holder.ans3.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.selected_ans_quiz)
else
holder.ans3.background = ContextCompat.getDrawable(parentFragment.requireContext(),R.drawable.default_ans_quiz)
holder.ans3.setOnClickListener {
shuffledAnswers[0].isSelected = false
shuffledAnswers[1].isSelected = false
shuffledAnswers[2].isSelected = true
mCallback.onClick(shuffledAnswers[2],position,it,holder.ans1,holder.ans2)
}
}
interface OnItemClickListener{
fun onClick(answerSelected: Answer?, questPosition: Int, selectedItemView: View, firstItemView: View, secondItemView: View)
}
QuizFragment.kt
mAdapter.setOnItemClickListener(object : QuizAdapter.OnItemClickListener{
override fun onClick(answerSelected: Answer?,
questPosition: Int,
selectedItemView: View,
firstItemView: View,
secondItemView: View) {
selectedItemView.background = ContextCompat.getDrawable(requireContext(),R.drawable.selected_ans_quiz)
firstItemView.background = ContextCompat.getDrawable(requireContext(),R.drawable.default_ans_quiz)
secondItemView.background = ContextCompat.getDrawable(requireContext(),R.drawable.default_ans_quiz)
quizViewModel.chosenAnswers[questPosition] = answerSelected
}
})

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.

Get the returned list from firestore based on condition when a value is passed to firestore function

I am trying to return a list from inside firestore function based on if a condition is true.I want to return different lists when different categories are selected.
I tried:
putting the return statement out of firestore function which did not work and returned empty list due to firestore async behaviour.
creating my own callback to wait for Firestore to return the data using interface as I saw in some other questions but in that case how am i supposed to access it as my function has a Int value(i.e.private fun getRandomPeople(num: Int): List<String>)?
What could be the way of returning different lists for different categories based on firestore conditions?
My code(Non Activity class):
class Board// Create new game
(private val context: Context, private val board: GridLayout) {
fun newBoard(size: Int) {
val squares = size * size
val people = getRandomPeople(squares)
createBoard(context, board, size, people)
}
fun createBoard(context: Context, board: GridLayout, size: Int, people: List<String>) {
destroyBoard()
board.columnCount = size
board.rowCount = size
var iterator = 0
for(col in 1..size) {
for (row in 1..size) {
cell = RelativeLayout(context)
val cellSpec = { GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL, 1f) }
val params = GridLayout.LayoutParams(cellSpec(), cellSpec())
params.width = 0
cell.layoutParams = params
cell.setBackgroundResource(R.drawable.bordered_rectangle)
cell.gravity = Gravity.CENTER
cell.setPadding(5, 0, 5, 0)
text = TextView(context)
text.text = people[iterator++]
words.add(text.text as String)
text.maxLines = 5
text.setSingleLine(false)
text.gravity = Gravity.CENTER
text.setTextColor(0xFF000000.toInt())
cell.addView(text)
board.addView(cell)
cells.add(GameCell(cell, text, false, row, col) { })
}
}
}
private fun getRandomPeople(num: Int): List<String> {
val mFirestore: FirebaseFirestore=FirebaseFirestore.getInstance()
val mAuth: FirebaseAuth=FirebaseAuth.getInstance()
val currentUser: FirebaseUser=mAuth.currentUser!!
var validIndexes :MutableList<Int>
var chosenIndexes = mutableListOf<Int>()
var randomPeople = mutableListOf<String>()
mFirestore.collection("Names").document(gName).get().addOnSuccessListener(OnSuccessListener<DocumentSnapshot>(){ queryDocumentSnapshot->
var categorySelected:String=""
if (queryDocumentSnapshot.exists()) {
categorySelected= queryDocumentSnapshot.getString("selectedCategory")!!
print("categoryselected is:$categorySelected")
Toast.makeText(context, "Got sel category from gameroom:$categorySelected", Toast.LENGTH_LONG).show()
when(categorySelected){
"CardWords"->{
for (i in 1..num) {
validIndexes=(0..CardWords.squares.lastIndex).toMutableList()
val validIndexIndex = (0..validIndexes.lastIndex).random()
val peopleIndex = validIndexes[validIndexIndex]
chosenIndexes.add(peopleIndex)
val person = CardWords.squares[peopleIndex]
randomPeople.add(person)
validIndexes.remove(peopleIndex)
peopleIndexes = chosenIndexes.toList()
}
}
else->{}
}
}
else {
Toast.makeText(context, "Sel category does not exist", Toast.LENGTH_LONG).show()
}
}).addOnFailureListener(OnFailureListener { e->
val error=e.message
Toast.makeText(context,"Error:"+error, Toast.LENGTH_LONG).show()
})
return randomPeople.toList()
}
}
Activity A:
Board(this, gridLay!!)

Categories

Resources