I have a MainAdapter.kt class that handles a RecyclerView. In its Holder class, I use a OnLongClickListener that calls a function deleteCategory(categoryId) to delete an entry in my Firebase database. This works perfectly:
class CategoryHolder(val customView: View, var category: Category? = null) : RecyclerView.ViewHolder(customView) {
private val TAG = CategoryHolder::class.java.simpleName
fun bind(category: Category) {
with(category) {
customView.textView_name?.text = category.name
customView.textView_description?.text = category.description
val categoryId = category.id
customView.setOnClickListener {
// do something
}
customView.setOnLongClickListener(
{
deleteCategory(categoryId)
true
}
)
}
}
private fun deleteCategory(categoryId: String) {
val database = FirebaseDatabase.getInstance()
val myRef = database.getReference("categories").child(categoryId)
myRef.removeValue()
Log.d(TAG, "Category with id " + categoryId + " deleted")
}
}
But I rather want to call a function inside a DialogFragment class instead of the deleteCategory(id) function, like this:
// Create an instance of a DeleteCategoryDialogFragment and show it
fun showDeleteCategoryDialog(view: View, categoryId: String) {
val dialog = DeleteCategoryDialogFragment.newInstance(categoryId)
dialog.show([email protected],
"DeleteCategoryDialog")
}
This gives me a "Unresolved reference: @MainActivity" error. How can I solve this? Is there a way to get hold of categoryId (of type String) in my MainActivity? This would allow me to move the function showDeleteCategoryDialog to MainActivity and solve the problem.
You can not refer to your MainActivity
like your code above. You have to cast the context
of your ViewHolder
as MainActivity
before using it:
val activity = itemView.context as? MainActivity
// then you can show your dialog with activity?.supportFragmentManager