How to make Recyclerview items clickable? - java

I am trying to make a notes app which will allows the user make simple notes and save it. I used realm database to save the users notes. The notes are showing up fine in the recyclerview but I cannot click them.
What I want to happen is, When one of the notes in the recyclerview is clicked I want to start a new acitivty.
adapter
class NotesAdapter(private val context:Context, private val notesList: RealmResults<Notes>):RecyclerView.Adapter<RecyclerView.ViewHolder>(){
private lateinit var mOnClickListener:View.OnClickListener
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.notes_rv_layout,parent,false)
v.setOnClickListener(mOnClickListener)
return ViewHolder(v)
}
override fun getItemCount(): Int {
return notesList.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
holder.itemView.titleTV.text = notesList[position]!!.title
holder.itemView.descTV.text = notesList[position]!!.description
holder.itemView.idTV.text = notesList[position]!!.id.toString()
}
private fun onClick(view:View) {
}
class ViewHolder(v: View?):RecyclerView.ViewHolder(v!!){
val title = itemView.findViewById<TextView>(R.id.titleTV)
val desc = itemView.findViewById<TextView>(R.id.descTV)
val id = itemView.findViewById<TextView>(R.id.idTV)
}
}
main activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//init views
realm = Realm.getDefaultInstance()
addNotes = findViewById(R.id.addNotes)
notesRV = findViewById(R.id.NotesRV)
//onclick add notes button
addNotes.setOnClickListener {
val intent = Intent(this, AddNotesActivity::class.java)
startActivity(intent)
finish()
}
notesRV.layoutManager = StaggeredGridLayoutManager(2,LinearLayoutManager.VERTICAL)
getAllNotes()
}
private fun getAllNotes() {
notesList = ArrayList()
val results:RealmResults<Notes> = realm.where<Notes>(Notes::class.java).findAll()
notesRV.adapter = NotesAdapter(this, results)
notesRV.adapter!!.notifyDataSetChanged()
}
}

use onBindViewHolder for that:
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
holder.itemView.titleTV.text = notesList[position]!!.title
holder.itemView.descTV.text = notesList[position]!!.description
holder.itemView.idTV.text = notesList[position]!!.id.toString()
holder.itemView.setOnClickListener{
val intent = Intent(holder.itemView.context,YourActivity::class.java)
holder.itemView.context.startActivity(intent)
}
}

Related

Error Updating Recycler View Item Button Visibility outside Adapter

My goal is to have button inside each RecyclerView item that will appear on click so Im changing the buttons visibility. On the first click it works fine but on clicking again or in any other item it crashes the app.
This is my Adapter.kt
class Adapter (private val orders:ArrayList<Order>, private val listener : OnItemClickListener) : RecyclerView.Adapter<Adapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_pedido,parent,false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentItem = orders[position]
holder.nrPedido.text = currentItem.id.toString()
holder.distancia.text = currentItem.distancia.toString()+"km"
holder.estado.text = currentItem.estado
}
override fun getItemCount(): Int {
return orders.size
}
inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener{
val nrPedido : TextView = itemView.findViewById(R.id.textViewIDPedido)
val distancia : TextView = itemView.findViewById(R.id.textViewDistancia)
val estado : TextView = itemView.findViewById(R.id.textViewEstado)
val buttonEstado : Button = itemView.findViewById(R.id.buttonEstado)
val buttonAceitarRecusar : Button = itemView.findViewById(R.id.buttonAceitarRecusar)
val buttonDados : Button = itemView.findViewById(R.id.buttonDados)
init {
itemView.setOnClickListener(this)
}
override fun onClick(p0: View?) {
val holder = ViewHolder(itemView)
val order = orders[adapterPosition]
val position = adapterPosition
if(position != RecyclerView.NO_POSITION && order != null) {
listener.onItemClick(order,position,holder)
}
}
}
interface OnItemClickListener{
fun onItemClick(order: Order,position: Int,holder: ViewHolder)
}
}
This Is my mainActivity where the onItemClick Method is being called
override fun onItemClick(order: Order,position:Int,holder: Adapter.ViewHolder) {
visible = visible?.not()
if(arrayListPedidos.contains(order)){
val clickedItem = arrayListPedidos[position]
if(visible==true){
holder.buttonDados.visibility = View.VISIBLE
}else{
holder.buttonDados.visibility = View.INVISIBLE
}
}else if(arrayListMeusPedidos.contains(order)){
val clickedItem = arrayListMeusPedidos[position]
if(visible==true){
holder.buttonDados.visibility = View.VISIBLE
}else{
holder.buttonDados.visibility = View.INVISIBLE
}
}
}
I think it could be something to do with not notifying that the item is being updated, but it could also be the way im sending the holder.
When I click one time on the item it changed the visibility to visible. If I click again (to make it invisible) or if I click in any other item it crashed the app.
Think about the ViewHolder as a highly volatile view, you don't want to keep any references about it that you use outside the Adapter – I see that you pass the ViewHolder back into the MainActivity if I understand correctly what you are trying to achieve could be done by doing something like this:
class Adapter(
private val orders: ArrayList<Order>,
// Note: Modern callbacks are declared like this, don't worry about passing the
// OnItemClickListener
private val listener: ((Order) -> Unit)
) : RecyclerView.Adapter<ViewHolder> { // Note: Try to use your own ViewHolders
// In situations like this you can use a map or some other data structure to keep track of what
// order button is supposed to be visible or not. You could also keep track of this in the Order
// class itself.
private val isVisibleMap = mutableMapOf<Int, Boolean>().apply {
orders.forEachIndexed { index, _ -> put(index, false) }
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_pedido,parent,false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentItem = orders[position]
// You must set the visibility during the binding
holder.buttonDados.visibility = if (isVisibleMap[position]) {
View.VISIBLE
} else {
View.GONE
}
holder.nrPedido.text = currentItem.id.toString()
holder.distancia.text = currentItem.distancia.toString()+"km"
holder.estado.text = currentItem.estado
holder.itemView.setOnClickListener {
// Here we update the visibility
isVisibleMap[position] = !isVisibleMap[position]
listener.invoke(currentItem)
}
}
override fun getItemCount(): Int {
return orders.size
}
inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView) {
val nrPedido : TextView = itemView.findViewById(R.id.textViewIDPedido)
val distancia : TextView = itemView.findViewById(R.id.textViewDistancia)
val estado : TextView = itemView.findViewById(R.id.textViewEstado)
val buttonEstado : Button = itemView.findViewById(R.id.buttonEstado)
val buttonAceitarRecusar : Button = itemView.findViewById(R.id.buttonAceitarRecusar)
val buttonDados : Button = itemView.findViewById(R.id.buttonDados)
}
}
Keep in mind that things like this, changing the visibility of an item from the adapter, should be handled within the adapter itself. Hope it helps!
Edit: If you want to change the button visibility programmatically from outside the Adapter, you can always do something like:
class Adapter ... {
fun changeButtonVisibility(isVisible: Boolean, pos: Int) {
isVisibleMap[pos] = isVisible
notifyItemChanged(pos)
}
}

ProgressBar not updating in RecyclerView item row

I'm uploading some photos to my server, and want to view the progress of individual uploads. However, my RecyclerView isn't updating.
I know the progress is being updated, as I can see the progress in the my upload task, and the photo is uploaded to the server. I thought the viewholder would be what I would use to update the view, but my progress listener isn't' called.
Does anyone see what I have done wrong? Or could do better?
The PhotoUploadItem is the object that gets updated with the progress.
class PhotoUploadItem(var photoStore: PhotoStore) {
interface PhotoUploadProgressListener {
fun onProgressChanged(progress: Int)
}
private var uploadProgress = 0
private var listener: PhotoUploadProgressListener? = null
fun setUploadProgress(uploadProgress: Int) {
this.uploadProgress = uploadProgress
listener?.onProgressChanged(uploadProgress)
}
fun subscribe(listener: PhotoUploadProgressListener) {
this.listener = listener
}
fun unsubscribe() {
this.listener = null
}
fun progress() = uploadProgress
fun identifier(): Int = photoStore.key
}
The PhotoUploadsAdapter takes a list of them.
class PhotoUploadsAdapter : RecyclerView.Adapter<PhotoUploadsAdapter.CustomViewHolder>() {
inner class CustomViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
private val differCallback = object : DiffUtil.ItemCallback<PhotoUploadItem>() {
override fun areItemsTheSame(oldItem: PhotoUploadItem, newItem: PhotoUploadItem) = oldItem.identifier() == newItem.identifier()
override fun areContentsTheSame(oldItem: PhotoUploadItem, newItem: PhotoUploadItem) = oldItem.hashCode() == newItem.hashCode()
}
val differ = AsyncListDiffer(this, differCallback)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
return CustomViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.row_photo_upload, parent, false))
}
override fun getItemCount() = differ.currentList.size
#SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
val item = differ.currentList[position]
holder.itemView.apply {
///..... set other fields
tvDisplayName?.text = item.photoStore.displayName
// THIS DOESN'T WORK
item.subscribe(object : PhotoUploadItem.PhotoUploadProgressListener{
override fun onProgressChanged(progress: Int) {
Log.i("UploadViewHolder", "${item.identifier()} has progress: $progress")
progressBar?.progress = progress
tvProgressAmount?.text = String.format(Locale.ROOT, "%d%%", progress)
}
})
}
}
}

How to notify and update list when item has been deleted using Groupie RecyclerView library and Kotlin

I have a RecyclerView implemented with the Groupie library and I can delete an item from the list fine, however need to update the view to see the change. I'd like to have something like notifyDataSetChanged() instead, so the list updates immediately. I'm a bit confused at this stage though, tried a few different ways to get an interface from the class that hosts my view holder to be triggered from the fragment that holds the adapter but I think I'm stuck now if I could get some help please.
class RecyclerProductItem(
private val activity: MainActivity,
private val product: Product, private val adapterListener: AdapterListener
) : Item<GroupieViewHolder>() {
companion object {
var clickListener: AdapterListener? = null
}
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
viewHolder.apply {
with(viewHolder.itemView) {
clickListener = adapterListener
ivTrash.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
if (clickListener != null) {
Toast.makeText(context, "delete method to be added here", Toast.LENGTH_SHORT).show()
clickListener?.onClickItem(position)
}
}
})
}
}
}
override fun getLayout() = R.layout.recyclerview_item_row
interface AdapterListener {
fun onClickItem(position: Int)
}
}
Here it's my fragment. I tried to add a section to the adapter to see if it would allow me to retrieve a listener for it, but as my listener should be triggered under a specific item within the layout, this may not be the best solution, although couldn't make this work either.
class ProductsListFragment : Fragment(), RecyclerProductItem.AdapterListener {
private lateinit var adapter: GroupAdapter<GroupieViewHolder>
private val section = Section()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_products_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val linearLayoutManager = LinearLayoutManager(activity)
recyclerView.layoutManager = linearLayoutManager
adapter = GroupAdapter()
adapter.add(section)
recyclerView.adapter = adapter
loadProducts()
}
private fun loadProducts() {
GetProductsAPI.postData(object : GetProductsAPI.ThisCallback {
override fun onSuccess(productList: List<JsonObject>) {
for (jo in productList) {
val gson = GsonBuilder().setPrettyPrinting().create()
val product: Product =
gson.fromJson(jo, Product::class.java)
adapter.add(
RecyclerProductItem(
activity as MainActivity,
Product(
product.id,
product.title,
product.description,
product.price
),adapterListenerToBePassedHere
)
) // This part is where I should be giving the listener, but get a red line since not sure how to get it to include it here.
}
}
})
}
companion object {
fun newInstance(): ProductsListFragment {
return ProductsListFragment()
}
}
override fun onClickItem(position: Int) {
adapter.notifyItemRemoved(position)
}
}
Many thanks.
I think you are missing this concept from the groupie Readme:
Modifying the contents of the GroupAdapter in any way automatically sends change notifications. Adding an item calls notifyItemAdded(); adding a group calls notifyItemRangeAdded(), etc.
So to remove an item, call section.remove(item). However, in your onClickItem function you currently only pass the position. Pass the item like clickListener?.onClickItem(this#RecyclerProductItem) instead.
Even more ideally and safely you should remove by product.id, e.g. clickListener?.onClickItem(this#RecyclerProductItem.product.id) then in onClickItem() you just search for the item with that product id and remove it. Let me know if I'm not clear.
Based on #carson's reply, this is what worked for me. Had to add the items to the section, the section to the adapter and then remove the item from the section based on the adapter position once that listener is clicked, passing the method that implements the listener as one of the arguments to complete the GroupAdapter.
class RecyclerProductItem(
private val activity: MainActivity,
private val product: Product, private val adapterListener: AdapterListener
) : Item<GroupieViewHolder>() {
companion object {
var clickListener: AdapterListener? = null
}
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
viewHolder.apply {
with(viewHolder.itemView) {
tvTitle.text = product.title
clickListener = adapterListener
ivTrash.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
if (clickListener != null) {
Toast.makeText(context, "delete method to be added here", Toast.LENGTH_SHORT).show()
clickListener?.onClickItem(this#RecyclerProductItem.product.id, adapterPosition)
}
}
})
}
}
}
override fun getLayout() = R.layout.recyclerview_item_row
interface AdapterListener {
fun onClickItem(id: Int, position: Int)
}
}
And
private fun loadProducts() {
GetProductsAPI.postData(object : GetProductsAPI.ThisCallback,
RecyclerProductItem.AdapterListener {
override fun onSuccess(productList: List<JsonObject>) {
Log.i(LOG_TAG, "onSuccess $LOG_TAG")
for (jo in productList) {
val gson = GsonBuilder().setPrettyPrinting().create()
val product: Product =
gson.fromJson(jo, Product::class.java)
val linearLayoutManager = LinearLayoutManager(activity)
recyclerView.layoutManager = linearLayoutManager
adapter = GroupAdapter()
section.add(
RecyclerProductItem(
activity as MainActivity,
Product(
product.id,
product.title,
product.description,
product.price
), this
)
)
adapter.add(section)
recyclerView.adapter = adapter
}
}
override fun onFailure() {
Log.e(LOG_TAG, "onFailure $LOG_TAG")
}
override fun onError() {
Log.e(LOG_TAG, "onError $LOG_TAG")
}
override fun onClickItem(id: Int, position: Int) {
section.remove(adapter.getItem(position))
}
})
}

Why does my Recyclerview add new items at random positions?

After much reading on how to add an item to the top (or bottom), I realized that list.add(position, item) along with notifyDataSetChanged() is the correct way to add an item at the top (index 0). However, in my code, even after doing that, my RecyclerView adds positions at random places. Below is my CommentsActivity code:
class CommentsActivity : AppCompatActivity() {
private var clickedPostUid = ""
private var currentUserUid = ""
private lateinit var binding_commentsActivity: ActivityCommentsBinding
private val currentUserUID = FirebaseAuth.getInstance().currentUser?.uid!!
private val dbRef = FirebaseDatabase.getInstance().reference
private val uidRef = currentUserUID.let { dbRef.child("Users").child(it) }
private var commentAdapterView: CommentsAdapter? = null
private var commentsList: MutableList<CommentsModel>? = null
var commentsActivityRecyclerView: RecyclerView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding_commentsActivity = ActivityCommentsBinding.inflate(layoutInflater)
clickedPostUid = intent.getStringExtra("keyIdentifierPostUid")!!
currentUserUid = intent.getStringExtra("keyIdentifierCurrentUserUid")!!
commentsActivityRecyclerView =
binding_commentsActivity.commentsActivityRecyclerView
val layoutManager = LinearLayoutManager(this)
layoutManager.reverseLayout = true
layoutManager.stackFromEnd = true
commentsActivityRecyclerView!!.layoutManager = layoutManager
commentsList = ArrayList()
commentAdapterView = CommentsAdapter(this, commentsList as ArrayList<CommentsModel>)
commentsActivityRecyclerView!!.adapter = commentAdapterView
commentsActivityRecyclerView!!.setHasFixedSize(true)
LoadAndDisplayComments()
And this is my LoadAndDisplayComments()
private fun LoadAndDisplayComments() {
val commentsRef = dbRef.child("Comments").child(clickedPostUid)
commentsRef.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
TODO("Not yet implemented")
}
override fun onDataChange(p0: DataSnapshot) {
if (p0.exists())
{
commentsList!!.clear()
for (snapshot in p0.children)
{
val getCommentDetails = snapshot.getValue(CommentsModel::class.java)
if (getCommentDetails != null) {
commentsList!!.add(0,getCommentDetails)
}
}
commentAdapterView!!.notifyDataSetChanged()
}
else{
Toast.makeText(this#CommentsActivity, "No comments" , Toast.LENGTH_SHORT).show()
}
}
})
}
This is my comments adapter
class CommentsAdapter(
private var commentsContext : Context,
private var commentsList: MutableList<CommentsModel>
) : RecyclerView.Adapter<CommentsAdapter.CommentsViewHolder>()
{
inner class CommentsViewHolder(#NonNull itemView: View) : RecyclerView.ViewHolder(itemView) {
val showComment : TextView = itemView.comments_recview_item_comment
val showImage : CircleImageView = itemView.comments_recview_item_profile_image
val showUsername : TextView = itemView.comments_recview_item_username
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentsViewHolder {
val itemView = LayoutInflater.from(commentsContext)
.inflate(R.layout.comment_recyclerview_item, parent, false)
return CommentsViewHolder(itemView)
}
override fun getItemCount(): Int {
return commentsList!!.size
}
override fun onBindViewHolder(holder: CommentsViewHolder, position: Int) {
val currentUser = FirebaseAuth.getInstance().currentUser!!
val comment = commentsList!![position]
holder.showComment.text = comment.comment
}
I need that a new comment to be displayed at the top or bottom of the recyclerview. I know how to scroll to 0 index using .SmoothScroll. Would be happy to post the XML if needed. Thank you.
Turns out the error was not in the RecyclerView. It was the way I was storing the values in the database. I was creating a unique Id for my values in Firebase that was causing the error. Instead I used .push to generate unique keys and it worked fine.
Wrong approach (or just not what I wanted):
val uniqueCommentId = UUID.randomUUID().toString()
.replace("-","").toUpperCase(Locale.ROOT)
val postCommentsRef = FirebaseDatabase.getInstance().reference
.child("Comments")
.child(postId).child(uniqueCommentId )
postCommentRef.setValue()
Better approach:
val postCommentsRef = FirebaseDatabase.getInstance().reference
.child("Comments")
.child(postId)
val commentMap = HashMap<String, Any>()
commentMap["userUid"] = currentUserUid
commentMap["postId"] = postId
commentMap["comment"] = comment
postCommentsRef.push().setValue(commentMap)
Worked fine for me after this.

RecyclerView adapter not working with groupie

I tried to add groupie adapter to my recycler view as shown in the code below. However when i run my application, i get a compiler error saying my reyclerview cannot be null (because of kotlin null safe feature). I cant figure out why this adapter is not working.
I know the problem is in the line :
recyclerview_newmessage.adapter = adapter
Here's the full code
class NewMessageActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.title = "Select User"
fetchUsers()
}
private fun fetchUsers() {
val ref = FirebaseDatabase.getInstance().getReference("/users")
ref.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
val adapter = GroupAdapter<ViewHolder>()
p0.children.forEach {
Log.d("NewMessage", it.toString())
val user = it.getValue(User::class.java)
if (user != null) {
adapter.add(UserItem(user))
}
}
recyclerview_newmessage.adapter = adapter
}
})
}
}
class UserItem(val user: User): Item<ViewHolder>() {
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.itemView.username_textview_new_message.text = user.username
}
override fun getLayout(): Int {
return R.layout.user_row_new_message
}
}
The final result show display the rows in the recycler view with the usernames that are in my firebase database.
If you define the recycler view in the xml file then you need to add it.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.ref_xml_file) . // add this line
supportActionBar?.title = "Select User"
fetchUsers()
}
if not define into the xml file.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var recyclerview_newmessage = RecyclerView(this)
setContentView(recyclerview_newmessage) . // add this line
supportActionBar?.title = "Select User"
fetchUsers()
}

Categories